What is the best way to set up Sinon to stub the console?

1,634 views
Skip to first unread message

Nicolas McCurdy

unread,
May 15, 2016, 7:17:25 PM5/15/16
to Mocha
I had some messy test code using sinon.test() where I would keep setting up the mocks all over again in each mocha example. Now I have my tests working with sinon sanbox setup in beforeEach() and afterEach() calls, but it seems like my stubs for console.log and console.error are actually stubbing away mocha's own output. As a result, these tests print the names of their contexts but mocha doesn't show the results of the individual examples.

Is there a better way to set up sinon stubs for the console in a beforeEach() call without affecting mocha's own output? I suppose I could change my implementation to use wrapper methods for console that I could stub separately from the console methods shared by mocha, but this feels messy to me.

Vlad GURDIGA

unread,
May 16, 2016, 5:01:57 AM5/16/16
to Mocha
Hi Nicolas! 8-)

Here is what I’d try:

    ~/tmp/mocha ω  cat test.js 
var assert = require('assert');
var sinon = require('sinon');

describe('code', function() {
  var printStub;

  beforeEach(function() {
    printStub = sinon.stub();
  });

  it('calls the print function', function() {
    runApp(printStub);

    assert(printStub.called, 'console.log was called');
  });
});

function runApp(print) {
  print('running the code');
}
    ~/tmp/mocha ω  mocha test.js 


  code
    ✓ calls the print function


  1 passing (7ms)

    ~/tmp/mocha ω  




Dependency injection FTW! 8-)
Reply all
Reply to author
Forward
0 new messages