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

How to test a method with timeout after calling another method in sinon

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

我想测试 属性 是否在 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 检查后 属性 测试没有改变。

非常感谢任何帮助!提前致谢。

只需更改此:

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

...为此:

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

...它应该可以工作。


详情

yieldsAsync 使用 process.nextTick 延迟,因此传递给 readFile 的回调直到 "all instructions in the current call stack are processed" 才被调用...在本例中是您的测试函数。

因此,将 afunc.test 更改为 'changed' 的回调被调用...但直到您的测试完成后才会被调用。