在摩卡下console.log单元测试失败,出现未知错误

时间:2019-04-22 00:50:19

标签: node.js unit-testing mocha console.log sinon-chai

我的单元测试无法执行以下代码。运行测试时,我看到以下结果,出现未知错误。我没有获得如何在console.log方法中测试第二个参数paylod。

Test console log()
-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    66.67 |      100 |        0 |    66.67 |                   |
 logger.js |    66.67 |      100 |        0 |    66.67 |                 6 |
-----------|----------|----------|----------|----------|-------------------|
npm ERR! Test failed.  See above for more details.

    //logger.js 
    'use strict';

    const log = (message, payload) => {
      console.log(message, JSON.stringify(payload, null, 2));
    };

    module.exports = { log };
    // log.test.js

    'use strict';

    const chai = require('chai');
    const sinon = require('sinon');
    chai.use(require('sinon-chai'));

    const { expect } = chai;
    const log = require('../../src/logger');

    describe('Test console log()', () => {
      it('should log value in console', () => {
        this.stub = sinon.stub(console, 'log');
        log('test invoked', { option: 1 });
      });
    });

1 个答案:

答案 0 :(得分:1)

看起来您只需要为require分解logger.js

'use strict';

const sinon = require('sinon');

const { log } = require('../../src/logger');  // <= destructuring assignment

describe('Test console log()', () => {
  it('should log value in console', () => {
    const stub = sinon.stub(console, 'log');
    log('test invoked', { option: 1 });
    stub.restore();
    sinon.assert.calledWith(stub, 'test invoked', JSON.stringify({ option: 1 }, null, 2));  // Success!
  });
});