簡體   English   中英

Angular - 如何使用異步服務調用對測試組件進行單元化

[英]Angular - How to unit test component with asynchronous service call

我有以下組件從Angular服務檢索數據:

export class MyComponent {
    constructor() {
        myService.get().then(() => {
            console.log('hello from constructor');
        });
    }
}

然后我的單元測試:

///////////

it('does something', () => {
    console.log('hello from unit test');
});

///////////

不幸的是,這導致以下日志:

> hello from unit test
> hello from constructor

如何在運行單元測試之前確保構造函數完成?

不要使用構造函數來加載數據,而是實現OnInit接口。

import { OnInit } from '@angular/core';
export class MyComponent implements OnInit {

    constructor(private myService: MyService) {}

    ngOnInit() {
        myService.get().then(() => {
            console.log('hello from constructor');
        });
    }
}
  • 另請參閱角度文檔Lifecycle Hooks
  • 不要忘記像myService實例那樣注入依賴項,我將它添加到構造函數中。

測試

我建議你閱讀測試文檔 這是很多信息,但值得。 以下是用於對組件進行單元測試的代碼。

let comp: MyComponent ;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
            providers: [
                { provide: MyService, useValue: {} }
            ]
        })
        .compileComponents(); 

    TestBed.compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
}));


it('initializes the component', fakeAsync(() => {
    var service = TestBed.get(MyService); // get your service
    service.get = () => {
            return Promise.resolve(); // you can pass data here if the service returns something
        };

    // here you could add an expect to validate component state before the call or service completes

    comp.ngOnInit(); // call ngOnInit
    tick(); // simulate the promise being resolved

    expect(service.get.toHaveBeenCalled);
    // here you could add an expect to validate component state after the service completes
}));

您的構造函數在測試之前正在執行,但是,構造函數的代碼會對服務進行異步調用,並在測試之后執行。

首先,您應該考慮將該服務調用從構造函數中移除。

其次,當你為一個組件編寫測試時,你經常監視服務調用並檢查它們是否被調用,你實際上並沒有進行調用,你可以模擬它。 查找“spyOn”的文檔。

最后,如果您想在測試之前發生某些事情,請查看'beforeEach'。 無論如何,希望這會有所幫助。

暫無
暫無

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

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