如何测试在jasmine 2.5中触发setTimeout的函数?

时间:2017-03-11 19:25:12

标签: javascript jasmine karma-jasmine

PlayOscillator(hz: number = 400, durationInSeconds: number = 1){
    this._Oscillators[0].frequency.value = hz;
    this._Oscillators[0].connect(this._MainGainNode);
    this._activeOscillatorIndex = 0;

setTimeout(() => {
    console.info("time out called");
    this._Oscillators[this._activeOscillatorIndex].disconnect(this._MainGainNode);
this._Oscillators[this._activeOscillatorIndex] = undefined;
}, durationInSeconds * 1000);
}

我想在执行setTimeout后测试typeof this._Oscillators[0],但我无法做到。我在这里找到的所有解决方案都推荐了jasmine 2.5中没有的功能

我到目前为止

       it('Should switch from one oscillator to another',()=>{
                let wap = webAudioApiProvider;
            expect(wap._Oscillators[0]).toBeUndefined();
            expect(()=>{wap.PlayOscillator(freq,duration)}).not.toThrow();
            expect(wap._Oscillators[0]).toBeUndefined();

        });

1 个答案:

答案 0 :(得分:0)

您应该能够使用自Jasmine 2.0以来支持的done参数:

it('Should switch from one oscillator to another', done => {
    let wap = webAudioApiProvider;
    expect(wap._Oscillators[0]).toBeUndefined();
    expect(()=>{wap.PlayOscillator(freq,duration)}).not.toThrow();

    setTimeout(() => {
        expect(wap._Oscillators[0]).toBeUndefined();
        done();
    }, duration * 1000 + 100); // add 100 to ensure this fires after the wap's timeout
});