Down the rabbithole

ekov @ pm.me

Mocking React components with props

In many cases, particularly in Gatsby, pages are wrapped in a <Layout> component. Today, I始ll describe a way to test these pages isolated from their wrapper.

A <Layout> component might look something like this simplified specimen:

export default function Layout({ children }) {
  return (
    <div>
      <SiteHeader />
      <main>{children}</main>
      <SiteFooter />
    </div>
  );  
}

As an example, let始s write a simple 404 page.

export default function NotFound() {
  return (
    <Layout>
      Sorry, this page does not exist. :(
    </Layout>
  );  
}

A test for our 404 page might look like the following, using Jest and react-testing-library:

describe('Not Found page', () => {
  it('shows a friendly message', () => {
    const { container } = render(<NotFound />);

    expect(container).toHaveTextContent('Sorry, this page does not exist');
  });
});

Let始s imagine Layout does a lot more than in our example. If we run the 404 Not Found test right now, it will fail miserably, because there始s a lot more going on in Layout than just putting things in a div. But that始s all we need from it in our test, so let始s do that!

Mocking the wrapper component *

Not much to change in our original test, we just have to mock Layout so it only returns a div with the children passed inside. This can be easily achieved like so:

jest.mock('./path/to/layout', () => props => <div {...props} />);

That始s it! This will 鈥渞ender鈥 in our test as:

<div>
  Sorry, this page does not exist. :(
</div>

As a result, our test will pass happily, because we are only testing the NotFound page itself, not caring about what happens in Layout.

Previous: Publishing an npm package
Next: