如何在sinon中调用另一个方法后测试一个带超时的方法

问题描述 投票:1回答:1

如何从另一个被调用的方法测试超时内的属性?

我想测试一个属性,如果它在setTimeout内被改变但是使用sinons useFakeTimer似乎不起作用。或者我错过了什么?

为了说明这里是我的代码

const fs = require('fs');

function Afunc (context) {
    this.test = context;
}

module.exports = Afunc;

Afunc.prototype.start = function () {
    const self = this;

    this.readFile(function  (error, content) {
        setTimeout(function () {
            self.test = 'changed';
            self.start();
        }, 1000);
    });
}

Afunc.prototype.readFile = function (callback) {
    fs.readFile('./file', function (error, content) {
        if (error) {
            return callback(error);
        }

        callback(null, content);
    })
}

这就是我到目前为止所拥有的。

describe('Afunc', function () {
    let sandbox, clock, afunc;

    before(function () {
        sandbox = sinon.createSandbox();
    });

    beforeEach(function () {
        clock = sinon.useFakeTimers();

        afunc = new Afunc('test');

        sandbox.stub(afunc, 'readFile').yieldsAsync(null);
    });

    afterEach(function () {
        clock.restore();
        sandbox.restore();
    });

    it('should change test to `changed`', function () {
        afunc.start();

        clock.tick(1000);

        afunc.test.should.be.equal('changed');

    });
});

clock.tick检查后,财产测试没有改变。

任何帮助深表感谢!提前致谢。

javascript unit-testing mocha settimeout sinon
1个回答
1
投票

只需改变这个:

sandbox.stub(afunc, 'readFile').yieldsAsync(null);

......对此:

sandbox.stub(afunc, 'readFile').yields();

......它应该有效。


细节

yieldsAsync推迟使用process.nextTick,因此传递给readFile的回调直到“当前调用堆栈中的所有指令都被处理”才被调用... ...在这种情况下是你的测试函数。

因此,将afunc.test更改为'changed'的回调被调用了......但是直到你的测试完成之后才开始。

© www.soinside.com 2019 - 2024. All rights reserved.