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

Oldest comments (0)