简体   繁体   English

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

[英]sinon not detecting private function called inside promise

i am quit new to sinon and rewire. 我不喜欢sinon并重新布线。 I am trying to check if private function was called with in promise. 我正在尝试检查是否在promise中调用了私有函数。 Private function stubbed is getting called, But sinon not detecting the call. 存根的私有函数被调用,但是sinon没有检测到该调用。 below is my code snipped. 下面是我的代码片段。

file.test.js 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 file.js

let otherFile = require('otherFile')

var privFunc = function(data) {

}

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

module.exports = {sampleFunc}

In above code snipped, privFunc is actually getting called ie. 在上面的代码片段中,privFunc实际上被调用即。 stub is getting called, But sinon not detecting call. 存根被调用,但是sinon没有检测到调用。


var privFunc = function(data) {

}

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

module.exports = {sampleFunc}

But this above snippet works fine. 但这上面的代码片段效果很好。 ie. 即。 when private function is called directly 直接调用私有函数时

Your otherFile.buildSomeThing is async, you need to await it before checking if the privFunc stub has been called. 您的otherFile.buildSomeThing是异步的,您需要先等待它,然后再检查privFunc存根是否已被调用。

eg: 例如:

file.js 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 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;
});

If you're using mocha, you could use something like this: 如果您使用的是摩卡咖啡,则可以使用以下方法:

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