当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to assert process.stderr output?

问题描述:

I'm building a little command line tool and I hit a problem with testing.

How can test that the current process wrote "omg" in stderr?

process.stderr.write("omg")

网友答案:

Install Mocha if you haven't:

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()    
    })
  })    
})

To run:

mocha test.js
网友答案:

You can temporary overwrite the process.stdout.write, buffer the input and use console.error to print the output (console.log will not work when process.stdout.write is overwritten), e.g.

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());
        });
    });
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: