Search code examples
reactjsnext.jsjestjsreact-testing-library

testing JSON ld script tag in next js HEAD component


we are using next js for our project. We add structured data with json+ld format using tag inside next js tag .

now we add this json ld script tag conditionally.

OurPage.tsx

 <Head>
<title>{"meta title"}</title>
      <meta name="description" content="meta desc"} />
{ structuredData && <Script
          nonce={nonce}
          type="application/ld+json"
          // eslint-disable-next-line react/no-danger
          dangerouslySetInnerHTML={{ __html: structuredData }}
        />}
    </Head>

now i am trying to test this behaviour using react testing library and jest with help of jest.mock("next/head") as below.

jest.mock('next/head', () => {
  return {
    __esModule: true,
    default: ({ children }: { children: Array<React.ReactElement> }) => {
      return <>{children}</>;
    },
  };
});

const {debug}
 render(<OurPage />);
debug();

the problem is that the render screen has only meta "title" and "description" tags and missing "script" tag that is supposed to be present.

does anyone know how to fix this ?


Solution

  • You can try adding data-testid="ldjson" to your script tag. I used here script tag, not the nextjs/script component as the eslint screams about it. But this script does not load anything so anyway it should be OK to use Script tag.

    <script
      data-testid="ldjson"
      type="application/ld+json"
      dangerouslySetInnerHTML={addJsonLd()}
    />
    

    and then in your test:

    const script = screen.getByTestId("ldjson");
    expect(script).toBeDefined();
    expect(script).toHaveTextContent("your expected value");
    

    it looks like the RTL debug method does not render the scripts.