Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, despite my efforts, I still see the "called getToken" console log when running the test.
I am aware that moving getToken to a separate file would solve this problem, but I am curious about why it isn't working in this scenario as it may occur frequently in the future.
export const getToken = async (params: {}): Promise<string> => {
try {
console.log("called getToken");
const oauthResponse = await axios.post(`url`, params);
return oauthResponse.data.token;
} catch (e) {
throw new Error("Exception caught getting token");
}
};
export const fetchData = async (params: {}): Promise<any> => {
try {
console.log("called fetchData");
const tokenValue = await getToken(params);
const response = await axios.post(`url`, params, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + tokenValue,
},
});
return response.data.body;
} catch (e) {
throw new Error("Exception caught");
}
};
This is how my handler.test.ts file looks like:
import { fetchData, getToken } from "./handler";
...
(getToken as jest.Mock).mockResolvedValue(mockedTokenValue);
(axios.post as jest.Mock).mockResolvedValue(response);
const result = await fetchData(params);
...
I've also attempted the following:
jest.mock(".handler", () => ({
...jest.requireActual("./handler"),
getSFEToken: jest.fn().mockImplementation(() => {
return "mocked_token";
})
}));
Here are snippets of my jest.config.ts and tsconfig.json for reference:
import type { Config } from "jest";
const config: Config = {
preset: "ts-jest",
testEnvironment: "node",
};
export default config;
{
"compilerOptions": {
"esModuleInterop": true,
"module": "commonjs",
"target": "es5",
"sourceRoot": "src",
"outDir": "dist",
"noImplicitAny": false,
...
],
...
}
}
Ps. I have referred to https://jestjs.io/docs/bypassing-module-mocks for guidance. Despite trying various mocking techniques and spies, the actual implementation of getToken is being called instead of the mocked value.