繁体   English   中英

Angular8单元测试jasmine超时问题

[英]Angular8 unit testing jasmine timeout issue

使用此故障模式运行随机单元测试失败

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

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

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

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

compileComponents的promise是否应该从回调中返回? 我在某处读到,异步包装器正在等待承诺,当承诺得到解决时,它最终调用 done()。 但是在这里,这个模式看起来它没有返回 promise,我们也没有在任何地方调用“await”关键字。 如果没有 return 语句,此代码是否会出现错误?

可以不返回 promise, async function负责等待在beforeEach中创建的所有承诺。 您可以在Angular 测试文档中看到该模式:

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

It's possible your IDE will complain, like WebStorm does, because it doesn't know the semantics of Angular's async function (notice this is not the same async keyword from JavaScript, this one is a function declared in Angular

关于您的原始错误,请尝试隔离失败的测试,或添加其中一个测试的示例,这些测试有时无法查看我们是否看到任何奇怪的东西。

您不需要它是异步的,您可以简单地删除异步 function 并使用createComponent(your_component)而不是compileComponents()进行同步(无论如何您都在等待它的解决方案)。 我可以确认这是有效的:

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

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM