【问题标题】:Assert that the function passed into a stubbed function is the correct function断言传递给存根函数的函数是正确的函数
【发布时间】:2019-09-12 10:39:03
【问题描述】:

我正在尝试使用 Mocha 测试我的 Node 模块。

模块很小,这里举个例子……

import { sharedFunctionA, sharedFunctionB, commonFunction } from <file>

const functionA = token => _data => sharedFunctionA(token);
const functionB = () => data => sharedFunctionB(data);

exports.doThingA = token => {
  commonFunction(functionA(token));
};

exports.doThingB = () => {
  commonFunction(functionB());
};

这只是一个简短的示例,但它显示了我正在尝试做的事情。

我需要测试doThingAdoThingB 是否将正确的函数传递给commonFunction

我已经对commonFunction 进行了存根,我可以看到它正在被调用,但我无法断言传入的函数是正确的。

TBH...我开始考虑完全重组它以将某种枚举传递给 commonFunction 并从那里运行相应的函数。

【问题讨论】:

    标签: node.js mocha.js sinon stub


    【解决方案1】:

    在这种情况下,您可以在 sharedFunctionAsharedFunctionB 上存根,然后在 commonFunction 上检索存根的参数并调用它。然后检查您的其他存根是否正在使用所需的参数调用。

    我知道这很乏味,但这是我能想到的使用您的代码的唯一方法。

    快速示例:

    const assert = require('assert')
    const sinon = require('sinon')
    const sharedFunctions = require('<fileWithSharedFunctions>')
    const commonStub = sinon.stub(sharedFunctions, 'commonFunction')
    const sharedBStub = sinon.stub(sharedFunctions, 'sharedFunctionB')
    
    const fileToTest = require('<fileToTest>')
    
    fileToTest.doThingB()
    commonStub.getCall(0).args[0]()
    assert(sharedBStub.calledOnce)
    

    【讨论】:

    • 啊!我没想到。谢谢,我试试看。
    • 我的做法略有不同,但现在可以正常工作了。谢谢:D
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2015-01-02
    • 2015-03-29
    相关资源
    最近更新 更多