Home > front end >  Jest mock variables of imported component
Jest mock variables of imported component

Time:01-04

I am trying to mock a variable (auth) inside my App component as it is doing conditional rendering. How should I do it without trying to export the variable itself? Been trying for a few days with various solutions but I can't seem to cover it, and now I am stuck.

App.js

import React from "react";
import { useRoutes } from "react-router-dom";
import Routing from "./routes";
import useAuth from "./hooks/useAuth";
import SplashScreen from "./components/splashScreen/SplashScreen";

const App = () => {
  const content = useRoutes(Routing());
  const auth = useAuth();

  return (
    <>
      {auth.isInitialized ? content : <SplashScreen />}
    </>
  );
};

export default App;

App.test.js

import React from "react";
import { mount } from "enzyme";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

describe("App Unit Tests", () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(
      <BrowserRouter>
          <App />
      </BrowserRouter>
    );
  });

  it("App should render", () => {
    expect(wrapper.length).toEqual(1);
  });

 //Below fails 
 it("should render splashscreen", () => {
    jest.mock("./hooks/useAuth", () => ({
      isInitialized: false,
    }));
    expect(wrapper.length).toEqual(1);
  });

  it("should render content", () => {
    jest.mock("./hooks/useAuth", () => ({
      isInitialized: true,
    }));
    expect(wrapper.length).toEqual(1);
  });
});

CodePudding user response:

You could do something like this:

jest.mock('./hooks/use-auth', () => ({
isInitialized: true
});

This basically means that use-auth returns an object which has a inInitialized property

CodePudding user response:

Instead of auth, the useAuth hook should be mocked into an object (say mockUseAuth) that has the isInitialized getter. The getter should return a mockIsInitialized value, that can be changed on per test case basis. Something like this :

let mockIsInitialized = true;

let mockUseAuth = {
  isAuthenticated: true
};

Object.defineProperty(mockUseAuth, 'isInitialized', {
  get: jest.fn(() => mockIsInitialized)
});

jest.mock('./hooks/use-auth', () => {
  return jest.fn(() => (mockUseAuth))
})

describe("App Unit Tests", () => {
 let wrapper;
 beforeEach(() => {
   wrapper = mount(
     <BrowserRouter>
       <App />
     </BrowserRouter>
   );
 });

 it("App should render", () => {
   expect(wrapper.length).toEqual(1);
 });

 it("should render splashscreen", () => {
   mockIsInitialized = false;
   expect(wrapper.length).toEqual(1);
 });

 it("should render content", () => {
   mockIsInitialized = true;
   expect(wrapper.length).toEqual(1);
 });
});
  •  Tags:  
  • Related