@@ -248,4 +248,81 @@ see https://github.com/mcollina/generify/blob/master/package.json
248248
249249 "test": "tape test.js | faucet"
250250
251-
251+
252+ ## stdout mock
253+
254+ 我们知道console.log是放到` process.stdout ` 里打印日志的方法,那么在单元测试里怎么测试呢?
255+
256+
257+ 这里给出一个机遇mocha的测试
258+
259+
260+ 思路很简单
261+
262+ - 通过captureStream方法来拦截stdout
263+ - 通过captureStream#captured获取stdout内容
264+
265+ 代码如下
266+
267+ ```
268+ var assert = require('chai').assert;
269+ var expect = require('chai').expect;
270+ require('chai').should();
271+
272+ var console = require('../index');
273+
274+ function captureStream(stream){
275+ var oldWrite = stream.write;
276+ var buf = '';
277+ stream.write = function(chunk, encoding, callback){
278+ buf += chunk.toString(); // chunk is a String or Buffer
279+ oldWrite.apply(stream, arguments);
280+ }
281+
282+ return {
283+ unhook: function unhook(){
284+ stream.write = oldWrite;
285+ },
286+ captured: function(){
287+ return buf;
288+ }
289+ };
290+ }
291+
292+
293+ describe('Console', function(){
294+ var hook;
295+
296+ before(function() {
297+ // runs before all tests in this block
298+ })
299+ after(function(){
300+ // runs after all tests in this block
301+ })
302+ beforeEach(function(){
303+ // runs before each test in this block
304+ hook = captureStream(process.stdout);
305+ })
306+ afterEach(function(){
307+ // runs after each test in this block
308+ hook.unhook();
309+ })
310+
311+ describe('#debug()', function(){
312+ it('should return a string when debug = true;', function(){
313+ console.debug = true;
314+ console.log("debug = true;");
315+
316+ assert.equal(hook.captured(),'debug = true;\n');
317+ })
318+
319+ it('should return empty string when debug = false;', function(){
320+ console.debug = false;
321+ console.log("debug = true;");
322+
323+ assert.equal(hook.captured(),'');
324+ })
325+ })
326+ })
327+ ```
328+
0 commit comments