我希望使用Jest模拟一个函数,但仅在它被调用时具有特定参数,例如:
function sum(x, y) {
return x + y;
}
// mock sum(1, 1) to return 4
sum(1, 1) // returns 4 (mocked)
sum(1, 2) // returns 3 (not mocked)
在 Ruby 的 RSpec 库中实现了类似的功能:
class Math
def self.sum(x, y)
return x + y
end
end
allow(Math).to receive(:sum).with(1, 1).and_return(4)
Math.sum(1, 1) # returns 4 (mocked)
Math.sum(1, 2) # returns 3 (not mocked)
我在测试中想要实现更好的解耦,比如说我想要测试一个依赖于sum
函数的函数:
function sum2(x) {
return sum(x, 2);
}
// I don't want to depend on the sum implementation in my tests,
// so I would like to mock sum(1, 2) to be "anything I want",
// and so be able to test:
expect(sum2(1)).toBe("anything I want");
// If this test passes, I've the guarantee that sum2(x) is returning
// sum(x, 2), but I don't have to know what sum(x, 2) should return
我知道可以通过类似以下方式来实现:
sum = jest.fn(function (x, y) {
if (x === 1 && y === 2) {
return "anything I want";
} else {
return sum(x, y);
}
});
expect(sum2(1)).toBe("anything I want");
但如果我们有一些糖函数来简化它,那就太好了。
这听起来合理吗?Jest中是否已经有了这个功能?
感谢您的反馈。
const functionResult = myFunc(args); expect(functionResult).toBe('whatever');
- paddotk