DEV Community

Daniel Nakamashi
Daniel Nakamashi

Posted on

1 2

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs