Unit testing react-helmet code

I was in a similar situation with react testing library and JSDOM, but I didn't want to make the test specific to the Helmet implementation because that's against the guiding principle of react testing library. I found that doing the obvious thing:

render(<App />)
await waitFor(...some DOM element)
expect(document.title).toEqual("title")

does not work even if the DOM element you're awaiting is rendered in the same render as the <Helmet>

However, this does work:

await waitFor(...some DOM element)
await waitFor( () => expect(document.title).toEqual("title"))

I presume that between React and Helmet there's some timing thing going on which means there's a delay between the rest of the DOM being rendered and the title being set in JSDOM.


Today i tested adding simply <HelmetProvider> in the return of the react function. Before that, i had errors like

TypeError: Cannot read properties of undefined (reading 'add')

when coming to the render command in the test. After adding the <HelmetProvider> tests are passed without error.


I figured out the answer myself. I did following:

it('should render metadata', () => {
    const wrapper = mount(<Metadata/>);
    // this will return all the markup assigned to helmet
    // which will get rendered inside head.
    const helmet = Helmet.peek();
    expect(helmet.title).to.equal("title");
});

This does the trick for unit test.