【问题标题】:How to test a method with timeout after calling another method in sinon在 sinon 中调用另一个方法后如何测试超时的方法
【发布时间】:2019-03-21 16:07:35
【问题描述】:

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

我想测试一个属性,如果它在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检查后属性test没有改变。

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

【问题讨论】:

    标签: javascript unit-testing mocha.js settimeout sinon


    【解决方案1】:

    只要改变这个:

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

    ...到这个:

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

    ...它应该可以工作。


    详情

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

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

    【讨论】:

    • 你是个救命的人!你应该喝新鲜的冰镇啤酒!非常感谢!
    • @per.eight 很高兴我能帮上忙 :)
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    相关资源
    最近更新 更多