I’m working with ts-jest and I have the following in handler.ts and I’m having trouble mocking the getToken function that’s being called inside fetchData, since I only want to test fetchData, I want to mock the response from getToken so it wouldn’t make the axios request, but somehow when I run the test I see the “called getToken” console.
I know that moving getToken to a different file would work but I want to understand why is this case not working since I might come across this scenario multiple times
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");
}
};
And this is my handler.test.ts
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 tried
jest.mock(".handler", () => ({
...jest.requireActual("./handler"),
getSFEToken: jest.fn().mockImplementation(() => {
return "mocked_token";
})
}));
This is my jest.config.ts and my 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,
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"declaration": false,
"listFiles": false,
"downlevelIteration": true,
"lib": [
"es5",
"es6",
"es2015",
"es2015.promise",
"dom",
"esnext.asynciterable"
]
},
"include": ["src/**/*"],
"exclude": [".vscode", ".serverless", ".git", "node_modules/**/*", "dist"],
"compileOnSave": true,
"buildOnSave": false,
"atom": {
"rewriteTsconfig": false
},
"baseUrl": "./",
"paths": {
"*": ["src/*"]
}
}
Ps. also reviewed this https://jestjs.io/docs/bypassing-module-mocks
Tried multiple mocking approaches and spies but the actual getToken implementation is being called rather than the mocked value