Testing next.js title using next/head with jest and react-testing-library giving false positives

Viewed 3667

I have started using Next.js in my newest project and I would like to implement some tests for the pages. I have created a _document file where I set up all of the meta tags which I want to use, including the title of the page.

<html>
<InlineStylesHead />

<body>
    <Main />
    <NextScript />

    <Head>
     <title>testing title</title>
    </Head>
</body>

</html>

then I set my test to render this page(which should include this _document as a part of it)

It's working as expected(including SSR).

So then I have tried to test it using react-testing-library and jest

here is my test:

it('should render the title', () => {
      render(<Page />);
      waitFor(() => {
          expect(document.title).toEqual('test title');
      });
});

Unfortunately, it's giving me false positives, and expect block is giving true no matter what. I have also tried to set the Head directly on the page, unfortunately, the same issue.

Have you used any other technique to test this kind of things? thanks!

1 Answers

expect doesn't give true, it's just ignored in the test. waitFor is asynchronous due to its nature and should be awaited in order to affect test result.

It should be:

it('should render the title', async () => {
      ...
      await waitFor(() => {
          expect(document.title).toEqual('test title');
      });
});
Related