How to test if function was called with defined parameters ( toHaveBeenCalledWith ) with Jest
OK, I've figured it out. The trick is, to split functions into separate files. So the code is (and works in https://repl.it/languages/jest ):
// add.js
child = require('./child').child;
function main(a) {
if (a == 2) {
child(a + 2);
}
return a + 1;
}
exports.main = main;
extracted child.js file:
// child.js
function child(ch) {
const t = ch + 1;
// no return value here. Function has some other "side effect"
}
exports.child = child;
main test file:
// add-spec.js
main = require('./add').main;
child = require('./child').child;
child = jest.fn();
describe('main', () => {
it('should add one and not call child Fn', () => {
expect(main(1)).toBe(2);
expect(child).toHaveBeenCalledTimes(0);
});
it('should add one andcall child Fn', () => {
expect(main(2)).toBe(3);
expect(child).toHaveBeenCalledWith(4);
expect(child).toHaveBeenCalledTimes(1);
});
});