distante distante - 9 months ago 23
Javascript Question

How to test a function that triggers a setTimeout in jasmine 2.5?

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);
}


I want to test
typeof
this._Oscillators[0]
after the setTimeout was executed but I am not able to do it. All the solutions that I have found here recommend functions that are not available in jasmine 2.5

I have so far

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();

});

Answer Source

You should be able to use a done parameter, which is supported since Jasmine 2.0:

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
});