是什么原因导致“当测试模块已实例化时无法配置测试模块”?

Sar*_*ste 15 testing angular

这是我的测试:

describe('ValueService', () => {

  it('#getValue should return real value', () => {
    expect(true).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

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

Sam*_*era 14

请注意,如果满足以下条件,即使您正确地使用了TestBed.configureTestingModule内部 a ,您也可能会遇到此错误describe

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

这个问题就在这里讨论。

修复方法是添加teardown: { destroyAfterEach: false }到您的模块配置中。

  • 这就是我需要的答案 - 谢谢! (4认同)

JFP*_*ard 13

正如与作者讨论的那样,当有两个或更多规范文件时在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();
  });
 });
Run Code Online (Sandbox Code Playgroud)

将实例化TestBedbeforeEach 测试,而不仅仅是规范文件。因此,如果您有另一个带有 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();
  });
 });
Run Code Online (Sandbox Code Playgroud)

错误

失败:当测试模块已实例化时,无法配置测试模块。

是对的,因为您实例化了两个 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();
  });
});
Run Code Online (Sandbox Code Playgroud)