I am writing unit tests for a function which calls another function inside the same module.
Eg.
export function add(a, b) {
return a + b
}
export function showMessage(a, b) {
let sum = add(a, b)
return `The sum is ${sum}`
}
Test:
import * as Logics from './logics;
describe('showMessage', () => {
it('should return message with sum', () => {
let addSpy = jest.spyOn(Logics, 'add')
let showMessageResponse = Logics.showMessage(2, 2)
expect(addSpy).toHaveBeenCalledTimes(1)
});
});
I want to test if the add function is being called when showMessage is executed. The above one is giving the following error:
Expected number of calls: 1 Received number of calls: 0
I have found a solution but that requires changes in the way functions are exported:
function add(a, b) {
return a + b
}
function showMessage(a, b) {
const sum = Logics.add(a, b)
return `The sum is ${sum}`
}
const Logics = {
showMessage,
add
}
export default Logics
I do not want to change the way I am exporting the functions.
Ideally you should test function independent. One test is not responsible for another function test functionality.
Not a best approach but you could do something like this:
util.js
export function add(a, b) {
return a + b;
}
export function showMessage(a, b, addNew = add) {
let sum = addNew(a, b);
return `The sum is ${sum}`;
}
And in your test you could do like this:
util.test.js
import * as Logics from "./util";
describe("showMessage", () => {
it("should return message with sum", () => {
let addSpy = jest.spyOn(Logics, "add");
addSpy.mockReturnValue(123);
let showMessageResponse = Logics.showMessage(2, 2, addSpy);
expect(addSpy).toHaveBeenCalledTimes(1);
expect(showMessageResponse).toBe(`The sum is 123`);
});
});
Here is the sandbox you can play with: https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With