I would like to make fun of the function with Jest, but only if it is called with specific arguments, for example:
function sum(x, y) { return x + y; }
A similar function is implemented in the Ruby RSpec library:
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)
What I'm trying to achieve in my tests is better to untie it, say, I want to test a function that relies on sum :
function sum2(x) { return sum(x, 2); }
I know that there is a way to implement this by doing something like:
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");
But it would be nice if we had the function of sugar to simplify it.
Does that sound reasonable? Do we already have this feature in Jest?
Thanks for your feedback.
javascript unit-testing jestjs
Nícolas Iensen
source share