繁体   English   中英

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

[英]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}

但这上面的代码片段效果很好。 即。 直接调用私有函数时

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM