Friday 27 March 2020

Problem testing a promise in a setInterval() with Mocha and Sinon

Hello, I'm having trouble for testing a property in a class which is regularly updated after requesting my database. My class looks like this:class Color { private _green: string = '' private async update() { const greenColor = await API.getGreenColor() this._green = greenColor } private regularUpdate() { setInterval(async() => { await this.update() }, 10000) } public async start() { await this.update() this.regularUpdate() } public get green() { return this._green } } What I've done to test 'start()' and it works:describe('start()', () => { it(`Should set the color`, async() => { sinon.stub(API, 'getGreenColor').resolves('green') const color = new Color() await color.start() expect(color.green).to.eql('green') }) }) Now what I'm doing to test the regular update and it fails:describe('regularUpdate()', () => { it(`Should regularly update the color`, async() => { const clock = sinon.useFakeTimers() const stub = sinon.stub(API, 'getGreenColor') stub.onCall(0).resolves('green') stub.onCall(1).resolves('darkGreen') const color = new Color() await color.start() expect(stub.calledOnce).to.be.true // <-- Passes expect(color.green).to.eql('green') // <-- Passes clock.tick(15000) console.log(color.green) // 'green' expect(stub.calledTwice).to.be.true // <-- Passes expect(color.green).to.eql('darkGreen') // <-- FAILS }) }) So the second call is called with the wrong data? Does anyone know why? I specify that if I use console.log to test "manually", the regular update works.

Submitted March 27, 2020 at 11:36PM by GreenMonkeyBoy

No comments:

Post a Comment