skip to Main Content

I have a Seo component that uses the next/head component. I would like to test this Seo component, but mocking next/head seems to do nothing at all. Am I doing something wrong?

import TestRenderer from 'react-test-renderer';
import Seo from '../Seo';

jest.mock(
  "next/head",
  () => function Head({ children }) {
    return children;
  },
);

it('should display seo', () => {
  const render = TestRenderer.create(
    <Seo />,
  );
  expect(render.toJSON()).toMatchSnapshot();
});
import Head from "next/head";

function Seo() {
  return (
    <Head>
      <title>Title SEO</title>
    </Head>
  );
}

2

Answers


  1. This works for me (remove typescript if just using js)

    jest.mock('next/head', () => {
      return {
        __esModule: true,
        default: ({ children }: { children: Array<React.ReactElement> }) => {
          return <>{children}</>;
        },
      };
    });
    
    Login or Signup to reply.
  2. I’m not sure if the test should be delayed to wait for the DOM manipulation to end. Also document.head might be needed to be provided as a container.

    it('should display seo', async () => {
      const render = TestRenderer.create(
        <Seo />, {container: document.head}
      );
      await waitFor(() => {
        expect(render.toJSON()).toMatchSnapshot();
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search