什么原因导致"Cannot configure the test module when the test module has already been instantiated"?



这是我的测试:

describe('ValueService', () => {
it('#getValue should return real value', () => {
expect(true).toBeTruthy();
});
});

我有这个错误:

失败:当测试模块已实例化时,无法配置测试模块。在R3TestBed.configureTestingModule之前,请确保您没有使用inject。 错误:当测试模块已实例化时,无法配置测试模块。在R3TestBed.configureTestingModule之前,请确保您没有使用inject

请注意,如果满足以下条件,即使您TestBed.configureTestingModule正确位于describe内,也可能会遇到此错误:

  1. 您的项目在 Angular 13+ 上
  2. 您正在使用 NgRx
  3. 您在测试中使用provideMockStore

此处讨论此问题。

解决方法是将teardown: { destroyAfterEach: false }添加到模块配置中。

正如与作者讨论的那样,当有两个或更多规范文件时,在describe之外初始化TestBed时,就会出现问题。

例如:

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
describe('AppComponent', () => {
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});

将在每次测试之前实例化TestBed,而不仅仅是规范文件。因此,如果您有另一个带有 TestBed 和 beforeEach 的 .spec,它将被解释为 2 个 TestBed,如下所示:

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
describe('AppComponent', () => {
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});

错误

失败:当测试模块具有 已被实例化。

是正确的,因为您实例化了两个测试平台(但在两个规范文件中(。

要解决此问题,您必须始终将TestBed定义(因此beforeEach(放在这样的描述中:

describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});

当我们在另一个描述中使用描述时,也可能发生这种情况,如下所示

describe('parent suite',()=>{
beforeEach(()=>{
// configure Testing module
// and some injections
})
// some tests....
describe('child suite',()=>{
beforeEach(()=>{
// here in parent suite if we perform any injections we have to use **TestBed.resetTestingModule()** before configuring another testing module`enter code here`
})

})
})
Hope this helps..

相关内容

最新更新