【问题标题】:What causes "Cannot configure the test module when the test module has already been instantiated"?什么原因导致“测试模块已经实例化时无法配置测试模块”?
【发布时间】:2020-09-09 09:58:51
【问题描述】:

这是我的测试:

describe('ValueService', () => {

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

我有这个错误:

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

【问题讨论】:

  • 请添加完整的规范文件内容
  • 嗨,Saroste,只是一个友好的提示,使用 CODE 按钮添加代码,这将对阅读您的帖子的人有很大帮助,并且更有可能获得帮助。
  • 感谢 mrbarletta @GérômeGrignon,我的规范文件中只有这个。
  • 它是唯一一个以 'fdescribe' 为焦点的测试吗?听起来您还有另一个缺少依赖项的测试也开始由业力触发。
  • 是的@GérômeGrignon,它是唯一的一个。如何识别缺少依赖项的测试?

标签: angular testing


【解决方案1】:

正如与作者讨论的那样,当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();
  });
 });

错误

失败:当测试模块有 已经实例化了。

没错,因为您实例化了两个 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();
  });
});

【讨论】:

    【解决方案2】:

    请注意,如果满足以下条件,您可能会遇到此错误,即使您将 TestBed.configureTestingModule 正确包含在 describe 中:

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

    这个问题在here讨论。

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

    【讨论】:

    • 这就是我需要的答案 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2015-01-02
    • 1970-01-01
    • 2013-04-09
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多