这是我的测试:
describe('ValueService', () => {
it('#getValue should return real value', () => {
expect(true).toBeTruthy();
});
});
我有这个错误:
失败:当测试模块已实例化时,无法配置测试模块。在
R3TestBed.configureTestingModule
之前,请确保您没有使用inject
。 错误:当测试模块已实例化时,无法配置测试模块。在R3TestBed.configureTestingModule
之前,请确保您没有使用inject
。
请注意,如果满足以下条件,即使您TestBed.configureTestingModule
正确位于describe
内,也可能会遇到此错误:
- 您的项目在 Angular 13+ 上
- 您正在使用 NgRx
- 您在测试中使用
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..