Javascript 使用Mocha从异步函数测试控制台输出(process.stdout.write)

Javascript 使用Mocha从异步函数测试控制台输出(process.stdout.write),javascript,node.js,mocha.js,Javascript,Node.js,Mocha.js,在node.js的异步函数中捕获process.stdout.write时遇到问题。我已经阅读了很多其他人的解决方案,我遗漏了一些显而易见的东西,但我不知道它是什么。我找到了适用于同步功能的解决方案,但无法使异步功能正常工作。我尝试了两种国产解决方案,以及test-console.js库 下面是我要测试的函数: const ora = require('ora') const coinInserted = (totalInserted) => { const spinner = or

在node.js的异步函数中捕获process.stdout.write时遇到问题。我已经阅读了很多其他人的解决方案,我遗漏了一些显而易见的东西,但我不知道它是什么。我找到了适用于同步功能的解决方案,但无法使异步功能正常工作。我尝试了两种国产解决方案,以及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);
};
库中的文档说要测试异步函数,如下所示:

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
  });
})
参考: