【问题标题】:Sinon delay callback functionSinon延迟回调函数
【发布时间】:2021-04-15 15:27:56
【问题描述】:

我只是想模拟延迟回调函数。我正在使用 sinon 和 mocha 进行测试。我更改了标准 fs 库的 readFile。我希望yields 函数在 5 秒后执行。因此,回调函数将在 5 秒后运行。但它没有用。当我在 fs.readFile 函数之前运行 yields 函数时,它起作用了。

function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

it.only('test stıb',  async () => {
    const stub = sinon.stub(fs, 'readFile');
    stub.withArgs('path', 'utf8');

    fs.readFile("path", "utf8", (err, data) => {
        console.log(data);
    });
    await sleep(5000);
    stub.yields(null, "Read File Message");
    stub.restore();
});

【问题讨论】:

    标签: node.js mocha.js sinon


    【解决方案1】:

    这似乎只是您的测试中的操作顺序问题。

    .yields 设置存根的行为。在你已经调用了你要测试的函数之后进行模拟是倒退的。

    function sleep(millis) {
        return new Promise(resolve => setTimeout(resolve, millis));
    }
    
    it.only('test stıb',  async () => {
        const stub = sinon.stub(fs, 'readFile');
        stub.withArgs('path', 'utf8');
        stub.yields(null, "Read File Message");
    
        await sleep(5000);
    
        fs.readFile("path", "utf8", (err, data) => {
            console.log(data);
        });
    
        stub.restore();
    });
    

    【讨论】:

    • 其实正是我想要的,回调函数应该在调用ReadFile函数后运行5秒。所以想在readFile函数中模拟繁重的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2011-09-14
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多