【发布时间】:2022-01-06 23:36:00
【问题描述】:
我最近开始将我的 Angular 应用程序和库转换为 @nrwl/nx 工作区。应用程序运行良好,但是在我的 Jest 测试中,我遇到了一些奇怪的错误。
工作区是使用
创建的标准 NX 工作区npx create-nx-workspace
生成的 jest 配置文件没有变化。
当我开始对我的一个库进行测试时
nx test my-lib-name
简单的测试运行良好。但是,当测试导入一些外部模块时,例如@ngx-translate/core/TranslateModule 或不同的 ngx-bootstrap 模块我收到以下错误:
由模块“DynamicTestModule”导入的意外值“TranslateModule”。请添加@NgModule 注解。
我的测试如下所示:
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();
});
});
我在 lib 中的 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(),
};
我已经搜索了很多,但找不到任何答案。我希望任何人都可以提供帮助。如果您需要更多信息,请告诉我。
【问题讨论】: