如何使process.stdout.write在mocha环境中工作?

时间:2015-10-05 09:46:24

标签: node.js mocha

我的脚本使用process.stdout.write生成输出。它需要使用process.stdout.write而不是console.log,因为console.log强制EOL

describe('process.stdout.write', () => {
    it('prints "foo"', () => {
        process.stdout.write('foo');
    });
});

打印:

process.stdout.write
    ✓ prints "foo"

1 passing (5ms)

请注意" foo"没有打印。

1 个答案:

答案 0 :(得分:0)

process.stdout.write与用于打印报告的mocha内部逻辑冲突。

要获得process.stdout.write的输出覆盖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());
        });
    });
});