在 module.exports 方法上使用 sinon 测试方法调用

Testing for method calls using sinon on module.exports methods

我正在尝试使用 mocha、chai 和 sinon 测试在特定条件下是否调用特定方法。这是代码:

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

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

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

这是我的测试文件中的代码:

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

当我对间谍执行 console.log 时,它说它没有被调用,即使你在 bar 方法中手动登录我也能看到它被调用。关于我可能做错了什么或如何解决的任何建议?

谢谢

您已经创建了一个 spy,但是测试代码没有使用它。用你的间谍替换原来的 x.bar(不要忘记做清理!)

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

});