使用`async`进行角度测试导致Jasmine超时?

时间:2018-06-07 17:56:50

标签: javascript angular typescript jasmine

我最近将一个项目升级到Angular 6,现在测试工作正常,现在失败了。以下是其中一项测试的示例:

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        declarations: [CampaignsDetailScheduleComponent],
        imports: [
          SomeModule,
          ReactiveFormsModule,
          TranslateModule.forRoot({
            loader: { provide: TranslateLoader, useClass: TranslateFakeLoader }
          }),
          StoreModule.forRoot({})
        ],
        providers: [{ provide: ConfigService, useValue: ConfigServiceMock }],
        schemas: [NO_ERRORS_SCHEMA]
      });
      fixture = TestBed.createComponent(CampaignsDetailScheduleComponent);
      comp = fixture.componentInstance; // Component test instance
      _store = fixture.debugElement.injector.get<Store<State>>(Store);
      comp.campaignModel$ = of(CampaignMockData);
      fixture.detectChanges();
    })
  );

it(
    'close edit schedule modal',
    async(() => {
      spyOn(_store, 'dispatch');
      comp.onClose();
      const args = new ShowHideEditScheduleModal(false);
      expect(_store.dispatch).toHaveBeenCalledWith(args);
    })
  );

Pre-Angular 6,此测试通过没有任何问题。但现在在Angular 6下,我收到错误:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.--Pendng async tasks are: [type: macroTask, source: setInterval, args: {handleId:4072,isPeriodic:true,delay:0,args:[object Arguments],__creationTrace__:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]},type: macroTask, source: setInterval, args: {handleId:4075,isPeriodic:true,delay:0,args:[object Arguments],__creationTrace__:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]}]

有没有人知道可能会发生什么?

2 个答案:

答案 0 :(得分:1)

在每个块之前使用fakeAsync代替async

答案 1 :(得分:0)

您可以通过执行

来增加默认的jasmine超时(即5s)间隔
it(
    'close edit schedule modal',
    async(() => {
      spyOn(_store, 'dispatch');
      comp.onClose();
      const args = new ShowHideEditScheduleModal(false);
      expect(_store.dispatch).toHaveBeenCalledWith(args);
   // increase default timeout interval to 10s
}), 10000);

或者你可以使用done()方法解决它。添加它将等待您的测试完成。我猜您在使用async

时无法使用done()
it('close edit schedule modal', (done) => {
          spyOn(_store, 'dispatch');
          comp.onClose();
          const args = new ShowHideEditScheduleModal(false);
          expect(_store.dispatch).toHaveBeenCalledWith(args);
          done();
       // increase default timeout interval to 10s
 }, 10000);