2017-08-08 100 views
3

我有一個方法被調用使用d3 timer。每當調用該方法時,該方法都會發出一個具有多個值的對象。 其中一個值隨着時間的推移而增加。我想寫一個測試來檢查這些值是否按照升序排列(即隨着時間的推移而增加)。規範沒有預期 - 茉莉花測試回調函數

所以,爲了解決這個問題,在我的測試中,我訂閱了事件發射器,並且在訂閱中,我將接收到的對象推送到本地數組中。然後,我期待array[i]小於array[i+1]。我認爲我的邏輯是完全正確的,但我不知道爲什麼我從Jasmine那裏得到一個錯誤,即使我有一個錯誤,也是the spec has no expectations

下面是代碼:

let x = d3.timer((elapsed) => { 
    this.method(); // call the function 
    if(elapsed >= 500) { 
    x.stop(); // stops the timer. 
    } 
}); 

method(elapsed) { 
// do something 
if(elapsed > 500) { 
    this.output.emit({x: somevalue, y: somevalue, f: increasingvalue }); 
} 
} 

茉莉花規格:

it('my spec', inject([JumpService], (service: JumpService) =>{ 
    array = []; 
    //service calls the method 
    service.output.subscribe(e => { 
    array.push(e); 
    // A console statement here will give me the length and the object pushed. 
    for(let i = 0; i< array.length - 1; i++) { 
    expect(array[i].f).toBeLessThan(array[i+1].f); 
    } 

    }); 

})); 

難道我做錯了什麼嗎?我怎樣才能解決這種情況?請指導我正確的方向。

謝謝。

回答

1

一般來說,在測試異步回調函數時,期望在promise完成後測試的輸出總是很重要的。您可以使用角試驗檯框架的tick()fakeAsync()或者你可以簡單地通過使用done()

使用done()退回到茉莉花的測試異步方法的一般方式:

it('my spec', (done) => { 
    array = []; 
    service.output.subscribe(e => { 
    array.push(e); 
    for(let i = 0; i< array.length - 1; i++) { 
    expect(array[i].f).toBeLessThan(array[i+1].f); 
    } 
    done(); 
    }); 
}); 

希望這個答案幫助。

注:我沒有與fakeAsync()tick()運氣很好,所以我沒有把它包括在答案中。對於那個很抱歉。

+0

Damnnn。 done()工作。很簡單。非常感謝。我完全放棄了它。乾杯。 – zelda