Categories
React Answers

How to mock React useRef or a function inside a functional component with enzyme and Jest?

Spread the love

To mock React useRef or a function inside a functional component with enzyme and Jest, we can mock the react module by mocking the useRef hook and getting the rest of the mocked module from the real module.

For instance, we write

import React, { useRef } from "react";
import { shallow } from "enzyme";
import Child2 from "./";

jest.mock("react", () => {
  const originReact = jest.requireActual("react");
  const mUseRef = jest.fn();
  return {
    ...originReact,
    useRef: mUseRef,
  };
});

describe("test", () => {
  it("should pass", () => {
    const mRef = { current: { offsetWidth: 100 } };
    useRef.mockReturnValueOnce(mRef);
    const wrapper = shallow(<Child2></Child2>);
    expect(wrapper.find("#myDiv").text()).toBe("123");
    expect(wrapper.find("p").text()).toBe("Div width is: 100");
  });
});

to mock the react module with jest.mock.

Then we call jest.requireActual to get the real react module.

We call mock with a function that returns the real react module except for the useRef hook which we set to a mocked function.

Then in our test, we call useRef.mockReturnValueOnce to return mRef as the mocked value and then run the rest of our test code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to mock React useRef or a function inside a functional component with enzyme and Jest?”

I’m not sure about that. How can I access a variable that is outside my current scope? I don’t think so

Leave a Reply

Your email address will not be published. Required fields are marked *