我只是想模拟延迟回调函数。我正在使用 sinon 和 mocha 进行测试。我更改了标准 fs 库的 readFile。我希望 yields
函数在 5 秒后执行。因此,回调函数将在 5 秒后运行。但它没有用。当我在 yields
函数之前运行 fs.readFile
函数时,它起作用了。
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();
});
答案 0 :(得分:0)
这似乎是您测试中的操作顺序问题。
.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();
});