我在 node.js 的异步函数中捕获 process.stdout.write 时遇到问题。我已经阅读了很多其他人的解决方案,并且遗漏了一些明显的东西,但我无法弄清楚它是什么。我找到了解决方案here这适用于同步功能,但无法使异步功能正常工作。我尝试过两种自行开发的解决方案以及 test-console.js 库。
这是我要测试的功能:
const ora = require('ora')
const coinInserted = (totalInserted) => {
const spinner = ora(' KA-CHUNK').start();
const output = `Amount Inserted: $${(totalInserted / 100).toFixed(2)}`;
setTimeout(() => {
spinner.text = ` ${output}`;
spinner.color = 'green';
spinner.succeed();
process.stdout.write('Please Insert Coins > ');
}, 500);
};
test-console.js 中的文档库说要测试异步函数,如下所示:
var inspect = stdout.inspect();
functionUnderTest(function() {
inspect.restore();
assert.deepEqual(inspect.output, [ "foo\n" ]);
});
...但我不明白 functionUnderTest 的语法。我认为我必须修改我正在测试的函数以接受回调函数,在其中我将调用测试(检查和断言)函数?但这似乎也不起作用。
最佳答案
由于您使用了setTimeout()
,我们可以使用sinon.useFakeTimers
来模拟超时。
这是示例
const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const succeedStub = sinon.stub(); // try to make the expectation this method is called
const index = proxyquire('./src', {
'ora': (input) => ({ // try to mock `ora` package
start: () => ({
text: '',
color: '',
succeed: succeedStub
})
})
})
describe('some request test', function() {
it('responses with success message', function() {
const clock = sinon.useFakeTimers(); // define this to emulate setTimeout()
index.coinInserted(3);
clock.tick(501); // number must be bigger than setTimeout in source file
assert(succeedStub.calledOnce); // expect that `spinner.succeed()` is called
});
})
引用:
关于javascript - 使用 Mocha 测试异步函数的控制台输出 (process.stdout.write),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054283/