2

我正在尝试提高此文件的测试覆盖率

'use strict'

/**
 * Returns the logging options we're using
 *
 * @param   {String} name Name of the logger. Should be service name. e.g. ciitizen-file-service
 * @returns {Object}      The logging options we're using
 * @private
 */
function getLoggerOptions(name) {
  return {
    name: name,
    streams: [
      {
        level: 'info',
        stream: stdOutStream()
      }, {
        level: 'error',
        stream: stdErrStream()
      }
      , {
        level: 'debug',
        stream: stdOutStream()
      },
      {
        level: 'warn',
        stream: stdOutStream()
      },
      {
        level: 'fatal',
        stream: stdErrStream()
      }
    ]
  }
}

/**
 * Creates a stream that writes to stdout
 *
 * @param   {Object} info The log info
 * @returns {Object}      An object which logs to stdout
 * @private
 */
function stdOutStream() {
  return {
    write: log => {
      // Change log level number to name and write it out
      log.level = bunyan.nameFromLevel[log.level]
      process.stdout.write(JSON.stringify(log) + '\n')
    }
  }
}

/**
 * Creates a stream that writes to stderr
 *
 * @param   {Object} info The log info
 * @returns {Object}      An object which logs to stderr
 * @private
 */
function stdErrStream() {
  return {
    write: log => {
      // Change log level number to name and write it out
      log.level = bunyan.nameFromLevel[log.level]
      process.stderr.write(JSON.stringify(log) + '\n')
    }
  }
}

module.exports = { getLoggerOptions }

我目前有这个测试

'use strict'

const expect = require('chai').expect
const { getLoggerOptions } = require('../src/helpers')

describe.only('#getLoggerOptions', () => {
  it('should return the logger options', () => {
    expect(getLoggerOptions('test')).to.be.an('object')
  })
})

这会在单元测试覆盖率方面产生这种差距在此处输入图像描述

我如何编写测试来覆盖此代码?

4

1 回答 1

1

您只是断言getLoggerOptions(...)应该返回一个对象,但您没有访问该对象。

例如,除了发布的测试之外,尝试添加如下测试:

describe.only('#probeLoggerOptions', () => {
  it('should do expected logging stuff', () => {
    const {name, streams} = getLoggerOptions('test');
    for (let stream of streams) {
      console.log(`getting logopt for level ${stream.level}`);
      expect(stream.stream.write(log), /* ... what to expect */);
    }
  });
});

现在测试正在调用write每个对象中的函数。

EXTRA:如果您拥有代码,最好的方法是重构它以使其更具可测试性。process例如,您可以创建一个WritableStream,写入它,然后通过管道传输到所需的流,而不是直接写入高级process流。

function configureStream(writable = process.stdout, data = null, msg = 'done') {
  const stream = fs.createReadStream('/tmp/log');
  stream.read(data);
  stream.pipe(writable);

}

function stdOutStream() {
  return {
    write: log => {
      // Change log level number to name and write it out
      log.level = bunyan.nameFromLevel[log.level];
      configureStream(data = JSON.stringify(log) + '\n');
    }
  }
}

除了能够configureStream单独测试之外,您还可以将每个日志记录过程的内容抽象为一个减少测试表面的函数。现在,您还可以连接到流的事件,例如“管道”或“完成”,以检查正在记录的内容。

于 2018-12-07T17:36:34.627 回答