I want to test, if particular function was called in my test and with the correct parameters. From JEST documentation I'm not able to figure out, what is the correct way to do it.
Let's say I have something like this:
// add.js
function child(ch) {
const t = ch + 1;
// no return value here. Function has some other "side effect"
}
function main(a) {
if (a == 2) {
child(a + 2);
}
return a + 1;
}
exports.main = main;
exports.child = child;
Now in unit test:
1.
I want to run main(1)
and test that it returned 2
and child()
was not called.
2.
And then I want to run main(2)
and thest that it returned 3
and child(4)
was called exactly once.
I have something like this now:
// add-spec.js
module = require('./add');
describe('main', () => {
it('should add one and not call child Fn', () => {
expect(module.main(1)).toBe(2);
// TODO: child() was not called
});
it('should add one andcall child Fn', () => {
expect(module.main(2)).toBe(3);
// TODO: child() was called with param 4 exactly once
// expect(module.child).toHaveBeenCalledWith(4);
});
});
I'm testing this in https://repl.it/languages/jest , so a working example in this REPL will be much appreciated.