DEV Community

Daniel Nakamashi
Daniel Nakamashi

Posted on

 

Unit Testing React HOC

Suppose we have the following HOC:

const withExtraProp = Component => props => {
  return <Component {...props} extraProp="extraValue" />;
};

As you may know, a component can be just a function and we can test it just like that. So we create a mock function and perform our test against that function.

const mockComponent = jest.fn(() => null);
const Component = withExtraProp(mockComponent);

render(<Component />);

await wait(() => expect(mockComponent).toBeCalled());

In the example above, we create a mock function that will be our component to be wrapped by withExtraProp. As this function represents a react component, it should return a component or null.

The return of withExtraProp is the mockComponent with props added to it. When we render this resulting component, it will call the function and we can test whether it was called.

We can also test if it was called with the right arguments.

const mockComponent = jest.fn(() => null);
const Component = withExtraProp(mockComponent);

render(<Component />);

await wait(() => expect(mockComponent).toBeCalled());
await wait(() => expect(mockComponent).toBeCalledWith({ extraProp: 'extraValue' }, expect.anything()));

The second argument expect.anything() is necessary because if you use forwardRef it contains the ref object.

What if there are other props passed to component?

Suppose you pass other props to component but you just want to test props passed by this specific HOC. You can use expect.objectContaining like this:

const mockComponent = jest.fn(() => null);
const Component = withExtraProp(mockComponent);

render(<Component normalProp="propValue" />);

await wait(() => expect(mockComponent).toBeCalled());
await wait(() => expect(mockComponent).toBeCalledWith(
  expect.objectContaining({ extraProp: 'extraValue' }),
  expect.anything()),
);

Here is the example working:
https://codesandbox.io/s/hopeful-curran-yb6cr?fontsize=14&hidenavigation=1

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React