我正在构建一个小命令行工具,我遇到了测试问题。
如何测试当前进程在stderr
中写了“omg”?
process.stderr.write("omg")
答案 0 :(得分:5)
如果您没有安装Mocha:
npm install -g mocha
<强> shouldpass.js:强>
process.stderr.write('omg')
<强> shouldfail.js:强>
process.stdout.write('not omg on stderr')
<强> test.js 强>
var exec = require('child_process').exec
, assert = require('assert')
describe('run tests', function(){
it('should pass', function(done) {
exec('node ./shouldpass.js', function(err, stdout, stderr) {
assert.equal(stderr, 'omg')
done()
})
})
it('should fail', function(done) {
exec('node ./shouldfail.js', function(err, stdout, stderr) {
assert.equal(stderr, 'omg')
done()
})
})
})
运行:
mocha test.js
答案 1 :(得分:0)
您可以临时覆盖process.stdout.write
,缓冲输入并使用console.error
打印输出(console.log
在覆盖process.stdout.write
时不起作用),例如
describe('process.stdout', () => {
let processStdoutWrite,
processStdoutWriteBuffer,
overwriteProcessStdoutWrite,
resetProcessStdoudWrite,
getProcessStdoutBuffer;
/**
* @var {function} Reference to the original process.stdout.write function.
*/
processStdoutWrite = process.stdout.write;
/**
* @returns {undefined}
*/
overwriteProcessStdoutWrite = () => {
processStdoutWriteBuffer = '';
process.stdout.write = (text) => {
processStdoutWriteBuffer += text;
};
};
/**
* @returns {string}
*/
getProcessStdoutBuffer = () => {
return processStdoutWriteBuffer;
};
/**
* @returns {undefined}
*/
resetProcessStdoudWrite = () => {
process.stdout.write = processStdoutWrite;
};
beforeEach(() => {
overwriteProcessStdoutWrite();
});
afterEach(() => {
resetProcessStdoudWrite();
});
describe('.write()', () => {
it('prints "foo"', () => {
process.stdout.write('foo');
process.stdout.write('bar');
console.error(getProcessStdoutBuffer());
});
});
});