Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for method calls using sinon on module.exports methods

I'm trying to test if a specific method is called given certain conditions using mocha, chai and sinon. Here is the code:

function foo(in, opt) {
    if(opt) { bar(); }
    else { foobar(); }
}

function bar() {...}
function foobar() {...}

module.exports = {
    foo: foo,
    bar: bar,
    foobar:foobar
};

Here is the code in my test file:

var x = require('./foo'),
    sinon = require('sinon'),
    chai = require('chai'),
    expect = chai.expect,
    should = chai.should(),
    assert = require('assert');

describe('test 1', function () {

  it('should call bar', function () {
      var spy = sinon. spy(x.bar);
      x.foo('bla', true);

      spy.called.should.be.true;
  });
});

When I do a console.log on the spy it says it wasn't called even thou with manual logging in the bar method I'm able to see it gets called. Any suggestions on what I might be doing wrong or how to go about it?

Thanks

like image 794
Toni Kostelac Avatar asked Mar 14 '23 09:03

Toni Kostelac


1 Answers

You've created a spy, but the test code doesn't use it. Replace the original x.bar with your spy (don't forget to do cleanup!)

describe('test 1', function () {

  before(() => {

    let spy = sinon.spy(x.bar);
    x.originalBar = x.bar; // save the original so that we can restore it later.
    x.bar = spy; // this is where the magic happens!
  });

  it('should call bar', function () {
      x.foo('bla', true);

      x.bar.called.should.be.true; // x.bar is the spy!
  });

  after(() => {
    x.bar = x.originalBar; // clean up!
  });

});
like image 116
Madara's Ghost Avatar answered Apr 06 '23 14:04

Madara's Ghost