簡體   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