运行 Jest 在@nrwl/nx 工作区中测试时出错

Error while running Jest tests in @nrwl/nx workspace

我最近开始将我的 Angular 应用程序和库转换为 @nrwl/nx 工作区。这些应用程序 运行 很好,但是当涉及到我的 Jest 测试时,我遇到了一些奇怪的错误。

工作区是使用

创建的标准 NX 工作区
npx create-nx-workspace

生成的 jest 配置文件没有变化。

当我使用

开始对我的一个库进行测试时
nx test my-lib-name

简单测试运行 很好。但是,当测试导入一些外部模块时,例如@ngx-translate/core/TranslateModule 或不同的 ngx-bootstrap 模块我收到以下错误:

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

我的测试是这样的:

import { ComponentFixture, waitForAsync, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { BsModalRef, ModalModule } from 'ngx-bootstrap/modal';

import { ErrorDialogComponent } from './error-dialog.component';

describe('ErrorDialogComponent', () => {
  let comp: ErrorDialogComponent;
  let fixture: ComponentFixture<ErrorDialogComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        ErrorDialogComponent,
      ],
      imports: [
        TranslateModule.forRoot(),
        ModalModule.forRoot()
      ],
      providers: [
        BsModalRef
      ]
    }).compileComponents()
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ErrorDialogComponent);
    comp = fixture.componentInstance;

    fixture.detectChanges();
  });

  it('should create component', () => {
    expect.assertions(1);

    expect(comp).toBeTruthy();
  });
});

我的 jest.config.js 里面的库是这样的:

module.exports = {
  displayName: 'my-lib-name',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/libs/my-lib-name',
  transform: {
    '^.+\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ]
};

全局 jest.presets.js 和 jest.config.js(自生成以来均未更改):

// jest.presets.js

const nxPreset = require('@nrwl/jest/preset');
module.exports = { ...nxPreset };



// jest.config.js

const { getJestProjects } = require('@nrwl/jest');
module.exports = {
  projects: getJestProjects(),
};

我已经搜索了很多但找不到任何答案。我希望任何人都可以提供帮助。如果您需要更多信息,请告诉我。

结果是一个依赖项(我不知道是哪个)被破坏或有问题。干净地重新安装所有依赖项修复了错误消息。