sinon未检测到内部承诺中的私有功能

时间:2019-07-24 15:17:35

标签: javascript node.js unit-testing sinon

我对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}

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

1 个答案:

答案 0 :(得分:0)

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

如果您使用的是摩卡咖啡,则可以使用以下内容:

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