在模块上使用sinon测试方法调用.出口的方法

Testing for method calls using sinon on module.exports methods

本文关键字:调用 出口 方法 测试方法 sinon 模块      更新时间:2023-09-26

我正在尝试测试是否在特定条件下使用摩卡,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;
  });
});

当我在spy上执行console.log时,它说它没有被调用,即使在bar方法中手动登录,我也能看到它被调用。有什么建议,我可能做错了或如何去做?

谢谢

您已经创建了一个spy,但是测试代码没有使用它。用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!
  });
});