我有函数 A,它从函数 B 获取值并将其与字符串进行比较。如果匹配则返回 true,否则返回 false。
function A(random) {
var something = B();
if (random === something) {
return true;
} else {
return false;
}
}
function B() {
var something = 'hello';
return something;
}
我的测试看起来像这样
test("Test ", function () {
//Arrange
var expected = true;
var random = "hi";
var B = sinon.stub();
B.returns(random);
//Act
var actual = A('hi');
//Assert
deepEqual(actual, expected);
});
我已经成功地使用 Sinon 删除了函数 B 以返回我选择的值。当我在测试中直接调用函数 B 时,它返回 stub 值,但是当我调用函数 A 时,它不再返回 stub 值,知道为什么吗?
最佳答案
您并不是真正 stub A
或 B
函数,只是创建一个具有相同名称的新本地函数。
如果你想注入(inject)(替换)函数,你必须以更加测试驱动的方式重构你的代码(即使用对象,没有本地函数,dependency inversion ...)。
或者使用类似 rewire
的工具修改本地模块范围变量并注入(inject) stub /假变量。
即
// same as require, but create a new copy (not cached)
// with __set__ and __get__ methods:
var myModule = rewire('./myModule')
, stubbedB = sinon.stub();
myModule.__set__("B", stubbedB);
myModule.__get__("A");
关于javascript - stub 函数在被另一个函数调用时不会返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266915/