javascriptunit-testingreactjsreact-helmet

Unit testing react-helmet code


I am using react-helmet to add elements to head element.

<Helmet>
     <title>title</title>
     <meta name="description" content="description" />
     <meta name="keywords" content="keywords" />
</Helmet>

And I am trying to write unit test like this:

it('should render metadata', () => {
    const wrapper = mount(<Metadata/>);
    // this is not working.
    expect(document.title).to.equal("title");
});

Solution

  • 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.