My project is a React application using Jest.
I have to test a function in which I am defining a const. The const is set using an imported service.
I want to mock the const in order to test the if-else statement
Here is the file I want to test:
import { authenticationService } from "../_services/authentication.service";
export const handleHeaders = (isFile = false) => {
const currentUser = authenticationService.currentUserValue;
if (currentUser && currentUser.access_token) {
return isFile
? {
Authorization: `Bearer ${currentUser.access_token}`,
"Content-Disposition": "multipart/form-data"
}
: {
Authorization: `Bearer ${currentUser.access_token}`,
"Content-Type": "application/json"
};
} else {
return { "Content-Type": "application/json" };
}
};
I tried to mock auth authentication service like below
import { handleHeaders } from "../handle-headers";
jest.mock("../../_services/authentication.service", () => ({
currentUserValue: { access_token: "some token" }
}));
describe("handleHeaders", () => {
it("should return headers with Authorization if
currentUser.access_token is defined", () => {
expect(handleHeaders()).toStrictEqual({
Authorization: "Bearer some token",
"Content-Type": "application/json"
});
});
});
But I get TypeError: Cannot read property 'currentUserValue' of undefined When the function tries to define const currentUser.
Thanks for your help