sinon 未检测到在 promise 中调用的私有函数

sinon not detecting private function called inside promise

我是 sinon 的新手并重新布线。我正在尝试检查 promise 是否调用了私有函数。存根的私有函数正在被调用,但是 sinon 没有检测到调用。下面是我的代码片段。

file.test.js

var fileController = rewire('./file')

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

file.js

let otherFile = require('otherFile')

var privFunc = function(data) {

}

var sampleFunc = function() {
    otherFile.buildSomeThing.then(function(data) {
        privFunc(data)
    })
}

module.exports = {sampleFunc}

在上面的代码片段中,privFunc 实际上被调用了。正在调用存根,但 sinon 未检测到调用。


var privFunc = function(data) {

}

var sampleFunc = function() {
    privFunc(data)
}

module.exports = {sampleFunc}

但是上面的这个片段工作正常。 IE。直接调用私有函数时

你的 otherFile.buildSomeThing 是异步的,你需要在检查 privFunc 存根是否被调用之前等待它。

例如:

file.js

let otherFile = require('otherFile')

var privFunc = function(data) {

}

var sampleFunc = function() {
    return otherFile.buildSomeThing.then(function(data) {
        privFunc(data)
    })
}

module.exports = {sampleFunc}

file.test.js

var fileController = rewire('./file')

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

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

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