2015-04-06 53 views
3

在我的JS测试中,我需要检查console.info是否被调用。这就是为什么我想模拟控制台。但是,看起来控制台变量不能被分配一个不同的对象。我犯了什么错误吗?我可以在NodeJs中嘲笑控制台吗?

这里是我使用的代码:

var oldConsole = console; 
var infoContent; 
console = { 
    info: function(content) { 
    infoContent = content; 
    } 
}; 

game.process('a command'); 
infoContent.should.equal('a command is processed'); 
console = oldConsole; 

回答

1

我找到解决方案。我可以更改控制台的方法信息。

console.info = function(content) { 
    infoContent = content; 
}; 

现在的问题是为什么控制台对象本身不能被重新分配?

+0

请参阅[我的评论](http://stackoverflow.com/a/30733360/2140627) – jamlen 2015-06-09 13:27:16

0

可以使用sinon NPM来调用计数功能:

it("calls the original function only once", function() { 
    var callback = sinon.spy(); 
    var proxy = once(callback); 

    proxy(); 
    proxy(); 

    assert(callback.calledOnce); 
    // ...or: 
    // assert.equals(callback.callCount, 1); 
}); 

你可以在这里找到文档:sinonjs.org

4

您可以使用rewire来取代中控台的整体沉默了,或者注入一个模拟。我使用deride,但sinon也会工作。

var rewire = require('rewire'); 
var deride = require('deride'); 
var Game = rewire('../lib/game'); 

describe('game testing', function() { 
    var stubConsole, game; 
    beforeEach(function() { 
    stubConsole = deride.stub(['info']); 
    stubConsole.setup.info.toReturn(); 
    Game.__set__({ 
     console: stubConsole 
    }); 
    game = new Game(); 
    }); 

    it('logs info messages', function() { 
    game.process('a command'); 
    stubConsole.expect.info.called.withArgs(['a command is processed']); 
    }); 
}); 
0

我以为我有同样的问题,我的解决办法就是用这个STD-嘲笑模块:

这具有不接管全球“控制台中的优势“但允许您查看记录到stdout/stderr的内容。这以不同于问题明确寻找的方式解决了问题;不过,我相信对于这个问题所暗示的问题来说,这是一个很好的答案,并且可能对其他人有用。

const stdMocks = require('std-mocks'); 
stdMocks.use(); console.log('test'); stdMocks.restore(); 
// => undefined [nothing gets output, stdout intercepted] 
const logged = stdMocks.flush(); 
console.log(logged) 
// => { stdout: [ 'test\n' ], stderr: [] } 
相关问题