Angular8单元测试茉莉花超时问题

时间:2019-10-08 18:38:18

标签: angular karma-jasmine angular-unit-test karma-jasmine-ajax

在这种故障模式下遇到随机单元测试故障

错误:超时-jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内未调用异步回调。

其中一些失败的测试甚至没有进行异步测试!​​

想知道这段代码是否正确;这是我们在Angular的所有测试中全面使用的一种模式

beforeEach(async(() => {
    TestBed.configureTestingModule({ . // Should this be **return TestBed.configureTestingModule**
      imports: [
        ...CommonTestModules
      ],
      declarations: [FooComponent]
    })
    .compileComponents();
  }));

是否应从回调中返回compileComponents的承诺?我读过某个地方,异步包装器正在等待这些诺言,当诺言被解决时,异步包装器最终会调用done()。但是在这里,这种模式似乎没有返回承诺,我们也没有在任何地方调用“ await”关键字。如果没有return语句,此代码会显示错误吗?

2 个答案:

答案 0 :(得分:0)

不返回该承诺是可以的,the async function负责等待在beforeEach内部创建的所有承诺。您可以在整个Angular Testing docs中看到该模式:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ BannerComponent ],
  })
  .compileComponents();  // compile template and css
}));

您的IDE可能会像WebStorm一样抱怨,因为它不知道Angular的async函数的语义(请注意,这与JavaScript中的async关键字不同,这是一个在Angular中声明的函数

关于您的原始错误,请尝试隔离出失败的测试,或者添加其中一个有时无法查看我们是否发现任何奇怪内容的测试的示例。

答案 1 :(得分:0)

您不需要异步,只需删除异步功能并使用createComponent(your_component)而不是compileComponents()进行同步即可(无论如何,您都在等待其解析)。我可以确认这项工作:

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [ BannerComponent ],
  });
  fixture = TestBed.createComponent(BannerComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

希望有帮助