2017-08-08 110 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