简体   繁体   中英

Can I mock console in NodeJs?

In my JS test, I need to check if the console.info is called. That's why I want to mock console. However, it seems that the console variable cannot be assigned with a different object. Did I make any mistake?

Here is the code I used:

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

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

You can use rewire to replace the whole of console to silence it, or to inject a mock. I use deride but sinon would also work.

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']);
  });
});

I find the solution. I can change the method info of console.

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

The question is now why console object itself cannot be reassigned?

you can use sinon npm to count the call to a function :

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

You can find the docs here : sinonjs.org

I thought I had the same problem and my solution was using this std-mocks module:

This has the advantage of not taking over the global "console" but allows you to see what gets logged to the stdout / stderr. This solves the problem in a different way than the question was explicitly looking for; however I believe it is a good answer for the problem the question implies and may be useful for others.

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: [] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM