Replies: 13 suggested answers 16 replies
-
| I don't think React Test Library    const renderComponent = ({ pageConfig, version }: Props) => {
   // Component will take the version and create a meta tag with it
    return render(<Index pageConfig={pageConfig} version={version} />)
  }
...
  it('should have a proper title', async () => {
    renderComponent({ pageConfig, version })
    await waitFor(() => {
      expect(document.querySelector('head')).toMatchSnapshot()
      // expect(document.title).toBe(pageConfig.title)
    })
  })The following snapshot have me Running  | 
Beta Was this translation helpful? Give feedback.
-
| @joshvillahermosa did you try with i got a simple Component that render meta tags depending on the  and this is the debug output. So it does render  | 
Beta Was this translation helpful? Give feedback.
-
| Hmm, I haven't tried that yet but I'll give it a try. Thanks!… On Fri, Jun 19, 2020, 2:08 PM Ethan ***@***.***> wrote:
 @joshvillahermosa <https://github.com/joshvillahermosa> did you try with
 await act(async () => {
   const { debug } = render(<Seo />, {
     container: document.head
   });
   debug();
 });
 i got a simple Component that render meta tags depending on the pathname
 that looks like this.
 import React, { useState, useEffect } from 'react';
 // next
 import NextSeo from 'next-seo';
 // hooks
 import { useLocation } from 'react-use';
 // helpers
 import { getSeoConfig } from 'src/helpers/seo';
 // constants
 import { BASE_SEO } from 'src/constants';
 const Seo: React.FC = () => {
   const [seo, setSeo] = useState(BASE_SEO);
   const state = useLocation();
   useEffect(() => {
     async function fetchSeo() {
       try {
         const data = await getSeoConfig(state.pathname);
         setSeo(data);
       } catch (error) {
         // TODO Sentry?
       }
     };
     fetchSeo();
   }, [getSeoConfig]);
   return (
     <>
       <title>Hello</title>
       <NextSeo
         config={seo}
       />
       <meta property="og:title" content="Test" />
     </>
   )
 };
 export default Seo;
 and this is the debug output.
  PASS  src/components/Seo.spec.tsx
   <Seo />
     ✓ show correct seo config (42 ms)
   console.log
     <head>
       <title>
         Hello
       </title>
       <meta
         content="Sapien"
         property="og:title"
       />
     </head>
 So it does render <head /> stuff but NextSeo /> its not rendering anything
 —
 You are receiving this because you were mentioned.
 Reply to this email directly, view it on GitHub
 <#11060 (comment)>,
 or unsubscribe
 <https://github.com/notifications/unsubscribe-auth/AAZXPZHFSJ6ONR4CV2UEHITRXOSRNANCNFSM4LHJV47A>
 .
 | 
Beta Was this translation helpful? Give feedback.
-
| I get to this test this morning and found a solution. you guys need to mock  and then simply do, for example. you can check how this is correctly render into the by doing  | 
Beta Was this translation helpful? Give feedback.
-
| @javidjamae can you open a code sandbox with this? or an example of how the  | 
Beta Was this translation helpful? Give feedback.
-
| My solution: jest.mock('next/head', () => {
  const ReactDOMServer = require('react-dom/server')
  return {
    __esModule: true,
    default: ({
      children,
    }: {
      children: Array<React.ReactElement> | React.ReactElement | null
    }) => {
      if (children) {
        global.document.head.insertAdjacentHTML(
          'afterbegin',
          ReactDOMServer.renderToString(children) || ''
        )
      }
      return null
    },
  }
})Can be added globaly for all tests     const tree = baseRender(<Component />)
    const head = tree.baseElement.parentElement?.firstChild as HTMLHeadElement
    expect(head).toMatchSnapshot()
    expect(tree.baseElement.parentNode).toMatchSnapshot()
    expect(
      head
        .querySelector('meta[name=robots]')
        ?.attributes.getNamedItem('content')?.value
    ).toBe('noindex,follow')
    expect(
      head
        .querySelector('meta[name=googlebot]')
        ?.attributes.getNamedItem('content')?.value
    ).toBe('noindex,follow')Snapshot:  | 
Beta Was this translation helpful? Give feedback.
-
| 
 next/head do not render headers immedialy. They collect all tags via context and render on App complete. https://github.com/vercel/next.js/blob/canary/packages/next/next-server/lib/head.tsx#L162-L174 | 
Beta Was this translation helpful? Give feedback.
-
| Has anyone figured out a solution for this yet? | 
Beta Was this translation helpful? Give feedback.
{{editor}}'s edit
{{editor}}'s edit
-
| import initHeadManager from 'next/dist/client/head-manager';
import { HeadManagerContext } from 'next/dist/shared/lib/head-manager-context';
import { useEffect } from 'react';
import ReactDOMServer from 'react-dom/server';
export const HeadWrapper: React.FC = props => {
  const { children } = props;
  const manager = initHeadManager();
  useEffect(() => {
    global.document.head.insertAdjacentHTML(
      'afterbegin',
      ReactDOMServer.renderToString(<meta name="next-head-count" content="0" />)
    );
  });
  return (
    <HeadManagerContext.Provider value={manager}>
      {children}
    </HeadManagerContext.Provider>
  );
};And test   it('renders a title', async () => {
    const episodes = getEpisodes();
    render(
      <EpisodePage
        episodes={episodes}
      />,
      { wrapper: HeadWrapper }
    );
    await waitFor(() => {
      expect(document.title).toEqual('Episode 1 - Peanutbutter girl comic');
    });
  });We need to use  | 
Beta Was this translation helpful? Give feedback.
-
| For anyone looking for a coming here from googling how to query element in the  import { render, within } from '@testing-library/react';
render(<TheThingThatRendersToHead data-testid="my-test-id" />);
const myThing = within(document.head).getByTestId('my-test-id'); | 
Beta Was this translation helpful? Give feedback.
-
| Looks like the HeadManager has changed in v12.2.0 and the  | 
Beta Was this translation helpful? Give feedback.
-
| I ended up mocking  // ./mocks/next/head.mock.ts
import type { FC } from "react";
import React from "react";
import ReactDOM from "react-dom";
const HeadMock: FC = ({ children }) => {
  return <>{ReactDOM.createPortal(children, document.head)}</>;
};
jest.doMock("next/head", () => HeadMock);Here's how I use it: import "./mocks/next/head.mock";
import Head from "next/head";
it("should set the page title", () => {
  render(
    <Head>
      <title>Hello world</title>
    </Head>
  );
  expect(document.head.querySelector("title")?.innerHTML).toEqual("Hello world");
}); | 
Beta Was this translation helpful? Give feedback.
-
| For Next.js 13  // ./src/app/head.tsx
export default function Head() {
  return (
    <>
      <title>Create Next App</title>
      <meta content="width=device-width, initial-scale=1" name="viewport" />
      <meta name="description" content="Generated by create next app" />
      <link rel="icon" href="/favicon.ico" />
    </>
  )
}// ./__test__/head.test.tsx
import { render } from '@testing-library/react';
import Head from '../src/app/head';
describe('Head', () => {
  it('renders correct title', () => {
    render(<Head />);
    expect(document.title).toBe('Create Next App');
  });
}); | 
Beta Was this translation helpful? Give feedback.
-
Hi,
We are using Next-SEO for metadata and structured data in our project, and I was wondering if anyone could help me to write a unit test to verify those elements.
Cheers,
Beta Was this translation helpful? Give feedback.