If you are setting a tag via JavaScript, for example, a description
metatag:
javascriptdocument.querySelector("meta[name='description']").content = 'Some random description';
If you are using Jest, you'll probably get an error while testing the component:
TypeError: Cannot set property 'content' of null metadata jest
To avoid it, create the metatag before testing the component using the beforeEach()
function in your test.
Example:
javascriptimport React from 'react'; import { BrowserRouter } from 'react-router-dom'; import { render, fireEvent, screen, waitFor } from '@testing-library/react'; import Component from '../Components/Component'; beforeEach(() => { var meta = document.createElement('meta'); meta.setAttribute('name', 'description'); document.head.appendChild(meta); }); test('modifies meta', async () => { render(<Component/>); await waitFor(() => expect(document.querySelector("meta[name='description']").content).toBe('Some random description')); });
Creating the metatag before running the test will prevent it to fail.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.