簡體   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