Angular mock Spec

1.6k views Asked by At

I am using ng-mocks this way -

import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ 
                      MockComponent(ComponentName),

      ],

      schemas:      [ NO_ERRORS_SCHEMA ]

    })
    .compileComponents();
  }));

I am seeing the below error -

Failed: ng-mocks is not in JIT mode and cannot resolve declarations
3

There are 3 answers

0
satanTime On BEST ANSWER

this issue has been fixed recently. In your case, it means that ComponentName has been imported wrongly, or has a wrong type.

MockComponent accepts classes. Therefore, it should be used like:

import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [ 
      MockComponent(ComponentClass), // <- its class instead of its name.
    ],
  }).compileComponents();
}));
1
V. Nogueira On

I got this error after upgrading my project from angular @12.2.16 to @13.2.4. However I was getting the exact same error:

MyComponent declaration has been passed into ng-mocks without Angular decorators. Therefore, it cannot be properly handled. Highly likely, jest.mock() has been used on its file, or ng-mocks is not in JIT mode

My project versions:

  • ng-mocks: 12.5.1
  • @angular/core: 13.2.4

After trying a lot of possible solutions a could solve my problem just reinstalling ng-mocks with the latest version and everything got fixed up and all tests were passing successfully.

Update ng-mocks to the latest version with:

$ npm uninstall ng-mocks
$ npm install ng-mocks@latest --save-dev

Good lucky, hope this help someone else.

0
Peter Kassenaar On

As an addition to the accepted answer: I also ran into the "...without Angular Decorators..." error.

In my case the embedded component was in its own module. I therefore had to import the module (or use MockModule instead of MockComponent) in the Testbed and everything worked smooth after that.