【问题标题】:Testing console output (process.stdout.write) from async functions using Mocha使用 Mocha 测试来自异步函数的控制台输出 (process.stdout.write)
【发布时间】:2018-10-29 21:43:48
【问题描述】:

我在 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的语法。我认为我必须修改我正在测试的函数以接受回调函数,在其中我将调用测试(检查和断言)函数?但这似乎也不起作用。

【问题讨论】:

    标签: javascript node.js mocha.js


    【解决方案1】:

    由于您使用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
      });
    })
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-02
      • 2012-08-22
      • 2014-02-08
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多