我正在尝试改善此文件的测试范围
'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')
})
})
中造成差距
我该如何编写测试以涵盖此代码?
答案 0 :(得分: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
函数。
额外:如果您拥有代码,则最好的方法是将其重构为更具可测试性。例如,您可以创建一个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
之外,您还可以将每个日志记录过程的内容抽象为一个减少测试面的函数。现在,您还可以加入流事件,例如“ pipe”或“ finish”,以检查正在记录的内容。