0
votes

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

1
May you show your effort to mock it? Have you looked at the jest docs?evolutionxbox

1 Answers

1
votes

You can use ES6 mocks: https://jestjs.io/docs/en/es6-class-mocks

Syntax:

jest.mock('../_services/authentication.service', () => ({
    __esModule: true,
    authenticationService: {
        currentUserValue: { access_token: 'some token' }
    }
}))

However, remember to call authenticationService.mockClear() in your beforeEach block to reset this between tests.

Edit: Because authenticationService isn't the default export, we need to mock it this way.