簡體   English   中英

如何對從服務訂閱 EventEmitter 的 angular 組件進行單元測試?

[英]How do I unit test an angular component that subscribes to an EventEmitter from a service?

我有一個看起來像這樣的組件:

export class MyComponent {
    myattr: boolean = true;
    constructor(public myService: MyService) {
        this.myService.stateUpdate.subscribe((event: number) => {
            this.myattr = event == 10;
        });
    }

服務:

export class MyService {
    stateUpdate: EventEmitter<number> = new EventEmitter<number>();
    onSomeEvent(): void {
        this.stateUpdate.emit(130);
    }
}

我的單元測試嘗試:

    beforeEach(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        component.myService = new MyService();
    });
    it("emitting 130 should set myattr to false", async()=>{
        component.myService.stateUpdate.subscribe((event: number) => {
            expect(event).toEqual(130); // this is detected correctly
        })
        component.myService.onSomeEvent();
        fixture.whenStable();
        expect(component.myattr).toEqual(false); // this does not work
    });

基本上,我想測試當subscribe內的任何代碼完成執行時會發生什么。 我該怎么做呢?

謝謝

在您的示例中,您創建服務並在組件創建后將其分配給 myService 屬性,因此構造函數中的訂閱是在另一個服務實例上進行的。 您可以在測試文件中創建服務實例或創建它的模擬,並在配置測試平台時通過 MyService 令牌提供它。 因此,您以后可以訪問該實例並在其上發出事件

你必須在fixture.whenStable().then()中做你的斷言

it("emitting 130 should set myattr to false", async(()=>{
    component.myService.onSomeEvent();
    fixture.whenStable().then(() => {
        expect(component.myattr).toEqual(false);
    });
});

請注意,Angular 的async()正在被waitForAsync()取代

在 Angular 官方文檔中,有一整節的常見測試場景可能會有所幫助:

https://angular.io/guide/testing-components-scenarios

在您的特定情況下,請查看這兩個小節以獲得完整的示例說明:

https://angular.io/guide/testing-components-scenarios#component-with-a-dependency

https://angular.io/guide/testing-components-scenarios#component-with-async-service

有不同的方法,但我通常做的是提供一個帶有測試主題的服務存根來發出值,然后在測試用例中使用 async 關鍵字,這樣我就可以在發出時期待結果。

暫無
暫無

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

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