console.log mocha 下的单元测试失败,出现未知错误

console.log unit test failing under mocha with unknown error

我的单元测试因以下 code.when 而失败,我 运行 测试我看到以下结果未知 error.I 我不知道如何在 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 });
      });
    });

看起来你只需要为 logger.js 解构你的 require:

'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!
  });
});