断言传递给存根函数的函数是正确的函数
Assert that the function passed into a stubbed function is the correct function
我正在尝试使用 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());
};
这只是一个简短的示例,但它展示了我正在尝试做的事情。
我需要测试 doThingA
和 doThingB
将正确的函数传递给 commonFunction
。
我已经标记了 commonFunction
,我可以看到它正在被调用,但我不能断言传入的函数是正确的。
TBH...我开始考虑完全重组它以将某种枚举传递给 commonFunction
和 运行 从那里各自的功能。
在这种情况下,您可以在 sharedFunctionA
和 sharedFunctionB
上存根,然后在 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)
我正在尝试使用 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());
};
这只是一个简短的示例,但它展示了我正在尝试做的事情。
我需要测试 doThingA
和 doThingB
将正确的函数传递给 commonFunction
。
我已经标记了 commonFunction
,我可以看到它正在被调用,但我不能断言传入的函数是正确的。
TBH...我开始考虑完全重组它以将某种枚举传递给 commonFunction
和 运行 从那里各自的功能。
在这种情况下,您可以在 sharedFunctionA
和 sharedFunctionB
上存根,然后在 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)