{ it('#getValue should return real value', () => { expe-6ren">
gpt4 book ai didi

angular - 是什么导致 "Cannot configure the test module when the test module has already been instantiated"?

转载 作者:行者123 更新时间:2023-12-04 12:35:42 27 4
gpt4 key购买 nike

这是我的测试:

describe('ValueService', () => {

it('#getValue should return real value', () => {
expect(true).toBeTruthy();
});
});
我有这个错误:

Failed: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.

最佳答案

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

  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 测试,不仅是规范文件。因此,如果您有另一个带有 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();
});
});
错误

Failed: Cannot configure the test module when the test module hasalready been instantiated.


会是对的,因为您实例化了两个 TestBed(但在两个规范文件中)。
要解决此问题,您必须始终放置 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();
});
});

关于angular - 是什么导致 "Cannot configure the test module when the test module has already been instantiated"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61957083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com