5

I'm getting the following error when running a test in Jest, using Angular 13:

 Unexpected value 'NgxsRootModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

      41 |
      42 |   beforeEach(() => {
    > 43 |     fixture = TestBed.createComponent(MyComponent);

which appears to be related to this beforeEach block that I have:

beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        imports: [
          FormComponentsModule,
          MatButtonModule,
          NoopAnimationsModule,
          ReactiveFormsModule,
          RouterTestingModule,
          MatSnackBarModule,
          MatIconModule,
          MatCardModule,
          NgxsModule.forRoot([])
        ],
        declarations: [MyComponent],
        schemas: [NO_ERRORS_SCHEMA],
        teardown: { destroyAfterEach: false }
      }).compileComponents();
    })
  );

But if I remove the forRoot([]) part it then just compains about NgxsModule in the same way.

This also works fine with Angular 11 & 12. It's only since upgrading to Angular 13 (which required upgrades of Jest to the latest version) that this problem has appeared.

Does anyone have any ideas as to why it now doesn't like the use NgxsRootModule?

eebsie
  • 396
  • 5
  • 18
  • Hi, I have the same issue. Have you found a solution? I am on Angular 14 and "jest-preset-angular": "~12.2.0", – Thabo Oct 19 '22 at 13:34

1 Answers1

8

First, you should update the jest-preset-angular plugin to the latest version.

After that in your ‘jest.config.js’ file, you need to have the line: globalSetup: 'jest-preset-angular/global-setup'

// jest.config.js
module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup'
};

Read more: https://thymikee.github.io/jest-preset-angular/docs/guides/angular-13+/

Tang Thanh Tam
  • 431
  • 3
  • 12
  • Simply adding: globalSetup 'jest-preset-angular/global-setup' to jest.config.js worked, thank you!! – jawn Sep 06 '22 at 13:48
  • It looks like the reason this works is because it runs a preprocessor that was removed in jest-preset-angular because ng14 doesn't need it. But since we have Ng12 libraries in the module being tested, it is still needed. – William Neely Oct 06 '22 at 15:21