最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Testing for method calls using sinon on module.exports methods - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Oct 26, 2015 at 8:10 Toni Kostelac asked Oct 22, 2015 at 10:11 Toni KostelacToni Kostelac 3613 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

});
发布评论

评论列表(0)

  1. 暂无评论