简体   繁体   中英

Mock a const defined in a function using Jest

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM