Testing method calls using synon using module.exports methods

I am trying to check if a particular method is being called under 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 the 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 console.log on a spy, it says that it was not called even with manual logging in the bar method, which I can see how it was called. Any suggestions on what I can do wrong or how to do it?

thanks

+4
source share
1 answer

You created spy, but the test code does not use it. Replace the original with x.baryour spy (do not forget to do the cleaning!)

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

});
+7

Source: https://habr.com/ru/post/1612735/


All Articles