Sinon 未检测到内部承诺调用的私有函数



我是Sinon 和 rewire 的新手。我正在尝试检查是否在承诺中调用了私有函数。正在调用私有函数存根,但 sinon 未检测到调用。下面是我截取的代码。

文件测试.js

var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc()
expect(stub).to.be.called

文件.js

let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
    otherFile.buildSomeThing.then(function(data) {
        privFunc(data)
    })
}
module.exports = {sampleFunc}

在上面的代码中,privFunc 实际上被调用了 ie. stub 正在被调用,但 sinon 没有检测到调用。


var privFunc = function(data) {
}
var sampleFunc = function() {
    privFunc(data)
}
module.exports = {sampleFunc}

但是上面的代码片段工作正常。 即当直接调用私有函数时

您的otherFile.buildSomeThing是异步的,您需要等待它,然后再检查是否已调用privFunc存根。

例如:

文件.js

let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
    return otherFile.buildSomeThing.then(function(data) {
        privFunc(data)
    })
}
module.exports = {sampleFunc}

文件测试.js

var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc().then(() => {
  expect(stub).to.have.been.called;
});

如果你使用的是摩卡,你可以使用这样的东西:

describe('file.js test cases', () => {
  let stub, reset;
  let fileController = rewire('./file');
  beforeEach(() => {
    stub = sinon.stub().returns("abc");
    reset = fileController.__set__('privFunc', stub);
  });
  afterEach(() => {
    reset();
  });
  it('sampleFunc calls privFunc', async () => {
    await fileController.sampleFunc();
    expect(stub).to.have.been.called;
  });
});

最新更新