I have my test case file set up like this:
const request = require("supertest");
const app = require("../app");
jest.mock("./addFunc", () => ({
addNumbers: jest.fn()
}));
...
test("Testing add function with double result", () => {
addNumbers.mockImplentation((a, b) =>
return 2 * (a + b));
let res = await request(app).post("/addNumbers").send({
a: 1,
b: 2
});
expect(res.body.result).toBe(6);
});
...
test("Testing add function with half result", () => {
addNumbers.mockImplentation((a, b) =>
return (a - b) / 2);
let res = await request(app).post("/addNumbers").send({
a: 6,
b: 2
});
expect(res.body.result).toBe(2);
});
...
The addNumbers
API I am calling contains addNumbers
function, which I want to mock with different implementations for different test cases like above. I took help from the most-voted answer of How to change mock implementation on a per single test basis?
But as I ran the test case, it threw error inside the test case that addNumbers
is not defined. However, if I don't write mockImplementation
inside test case and mock the addNumbers
on top of the file, then it works fine. But in that case how would I rewrite the mock for a different test case?
I am not able to figure it out because addNumbers
has already been defined on top of the file.