'Next seo test with react testing library
I am trying to test my SEO component which looks like this:
export const Seo: React.FC<Props> = ({ seo, title, excerpt, heroImage }) => {
const description = seo?.description || excerpt
const pageTitle = seo?.title || title
const router = useRouter()
return (
<NextSeo // https://www.npmjs.com/package/next-seo
canonical={seo?.canonical}
nofollow={seo?.nofollow}
noindex={seo?.noindex}
title={pageTitle}
description={description}
openGraph={{
title,
description,
type: "article",
...
and my test is like so:
describe("Seo", () => {
it("should render the meta tags", async () => {
const props = {
title: "title page",
excerpt: "string",
seo: {
title: "seo title",
description: "meta description",
},
heroImage: {
src: "url",
alt: "alt text",
width: 300,
height: 400,
},
}
function getMeta(metaName: string) {
const metas = document.getElementsByTagName("meta")
for (let i = 0; i < metas.length; i += 1) {
if (metas[i].getAttribute("name") === metaName) {
return metas[i].getAttribute("content")
}
}
return ""
}
render(<Seo {...props} />)
await waitFor(() => expect(getMeta("title")).toEqual("title page"))
})
})
however the test is failing: (it looks like the head element is empty)
Solution 1:[1]
in JS
jest.mock('next/head', () => {
return {
__esModule: true,
default: ({ children }) => {
return children;
}
};
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Cordano |

