【问题标题】:sinon not detecting private function called inside promisesinon 没有检测到内部调用的私有函数
【发布时间】:2019-07-24 23:50:12
【问题描述】:

我对 sinon 不熟悉,重新接线。我正在尝试检查是否在承诺中调用了私有函数。私有函数存根被调用,但 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

文件.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}

但是上面的 sn-p 工作正常。 IE。直接调用私有函数时

【问题讨论】:

  • 除非 sampleFunc 返回它正在创建的承诺,否则您将不知道 何时 来检查存根是否被调用。 otherFile.buildSomeThing 是异步的。
  • @MarkMeyer,对不起,请详细说明一下,buildSomeThing 是来自不同模块的函数,它返回实际成功解决的承诺
  • buildSomething 可能会返回一个承诺,但 sampleFunc 不会返回任何内容。因此,当您致电sampleFunc 时,您无法知道buildSomething 何时结束。您需要能够致电sampleFunc.then(() => test_if_stubb_is_called)。为此sampleFunc 需要返回承诺return otherFile.buildSomeThing.then(...
  • @MarkMeyer,是的,我犯了不等待 fileController.sampleFunc() 的愚蠢错误。现在它工作正常。谢谢,请发布您的答案。

标签: javascript node.js unit-testing sinon


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 2021-02-20
    • 2020-12-30
    • 2015-07-04
    • 2018-10-21
    • 1970-01-01
    • 2017-08-01
    • 2015-10-10
    相关资源
    最近更新 更多