2017-07-04 12 views
1

我正在使用Karma-Jasmine爲我的component(Angular2應用程序)編寫unit test。 Code Coverage報告使用Istanbul使用Spyon時的代碼覆蓋問題

這裏是我的測試情況下,

it('Should Invoke onNext function', async(() => { 
    const fixture = TestBed.createComponent(LoginComponent); 
    fixture.detectChanges(); 
    const login = fixture.componentInstance; 

    spyOn(login, 'onNext'); 

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']"); 
    email.value = "email"; 

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1]; 
    nextButton.click(); 

    fixture.whenStable().then(() => { 
     expect(login.onNext).toHaveBeenCalled(); 
    }) 
    })); 

正如你看到的我是spying on onNext function,以驗證它是否過得好nextbutton click稱爲與否。它工作正常,測試通過。

但是我的登錄頁面的代碼覆蓋率報告顯示onNext函數沒有被覆蓋。 enter image description here

我在做什麼錯?

並且如果我不上onNext窺視功能,功能覆蓋,

it('Should Invoke onNext function', async(() => { 
    const fixture = TestBed.createComponent(LoginComponent); 
    fixture.detectChanges(); 
    const login = fixture.componentInstance; 


    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']"); 
    email.value = "email"; 

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1]; 
    nextButton.click(); 
    })); 

enter image description here

+1

因爲間諜實際上是替換函數調用。你必須做兩個測試:第一個測試是否實際調用函數(你做了什麼),第二個測試你的onNext函數。 – trichetriche

+0

不知道..謝謝你的信息。有沒有更好的方法來做到這一點?這樣我可以在同一時間實現兩個? – Vinay

+0

是的,把它們放在同一個'it'中(儘管我不會推薦它)。順便說一句,調用'component.onNext()'將覆蓋它的代碼覆蓋範圍,但它不是測試!測試意味着你必須使用斷言來測試你是否得到正確的值 – trichetriche

回答

3

使用此:

spyOn(login, 'onNext').and.callThrough()

+0

正是我想要的..謝謝 – Vinay