如何断言process.stderr输出?

时间:2013-01-18 17:25:18

标签: javascript node.js testing io tdd

我正在构建一个小命令行工具,我遇到了测试问题。

如何测试当前进程在stderr中写了“omg”?

process.stderr.write("omg")

2 个答案:

答案 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());
        });
    });
});