在process.stdout.write中的异步函数中捕获node.js存在问题。我读过很多其他人的解决方案,我忽略了一些显而易见的东西,但我不知道它是什么。我找到了适用于同步函数的解决方案这里,但无法使异步工作。我已经尝试过国产的解决方案,以及测试控制台as库。
下面是我要测试的函数:
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" ]);
});...but我不懂functionUnderTest的语法。我认为我必须修改正在测试的函数以接受回调函数,在其中我将调用测试(检查和断言)函数?但这似乎也行不通。
发布于 2018-10-30 01:20:27
因为您使用了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
});
})参考:
https://stackoverflow.com/questions/53054283
复制相似问题