2013-01-18 72 views

回答

5

安裝摩卡如果你還沒有:

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