簡體   English   中英

有兩個條件的 Karma 單元測試 IF

[英]Karma unit testing IF with two conditions

我正在編寫單元測試,我有點堅持這種方法。 我有從 formGroup 獲取名稱的 onClickCheck 方法(這部分我在測試中介紹),然后檢查 data.action 是否等於 NEW 以及 name 是否存在,然后執行某些操作。

onClickCheck() {
    const name = this.formGroup.get('name').value;


    if (this.data.action === 'NEW' && name) {
        this.service
            .doSomething(name)
            .pipe(take(1))
            .subscribe((result: any) => {
                this.someVar = result.data.attributes;

                if (this.someVar.isDeleted) {
                    this.confirmationDialog(dialogData);
                }
            });
    }
}

在我的測試中,我嘗試這樣做,但出現錯誤:expect(spy).toHaveBeenCalled() 但調用次數為 0。

const doSomethingSpy = spyOn(
            service,
            'doSomething'
        ).and.callThrough();

        component.formGroup.setValue({
            name: 'Test',
            lastName: 'TT2'
        });

        component.data= {
            action: 'NEW',
            item: null
        };

        const name = component.formGroup.get('name').value;

        component.onClickCheck();
        fixture.detectChanges();
        expect(doSomethingSpy ).toHaveBeenCalled();

如何在這個雙重條件 IF 中測試代碼?

const name = component.formGroup.get('name ').value;

可能是因為您在測試中正在尋找“名稱”而不是“名稱”嗎?

暫無
暫無

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

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