簡體   English   中英

在 Karma 4 / Angular 7 中執行測試之前等待注入服務的構造函數完成

[英]Wait for constructor of injected service to finish before executing tests in Karma 4 / Angular 7

我正在注入這樣的服務:

it('name of test', inject([ Service], (hcs: Service) => {
    const pipe = new MyPipe(hcs);
    const expectedResult = ...
    //Here the constructor of the hcs-service has to be completet, otherwise the Pipe fails
    const result = pipe.transform(...);
    expect(result).toEqual(expectedResult);
}));

在開始執行管道的轉換方法之前,我需要運行服務的構造函數。 在運行時,這不是問題,因為此管道始終是對用戶操作的反應。 但是在我的測試中,它失敗了,因為構造函數還沒有運行。

什么是解決這個問題的好方法?

編輯:正如 Arif 在評論中指出的那樣。 問題是我的構造函數執行異步任務。 謝謝 :)

對象的構造函數將始終首先執行。 除非你有異步代碼。

正如您在評論中提到的那樣,這是您的案例中的問題。

要在測試中等待異步功能完成,您必須使用fakeAsync勾選

it('name of test', fakeAsync(inject([ Service], (hcs: Service) => {
    const pipe = new MyPipe(hcs);

    tick();

    const expectedResult = ...
    //Here the constructor of the hcs-service has to be completet, otherwise the Pipe fails
    const result = pipe.transform(...);
    expect(result).toEqual(expectedResult);
})));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM