[英]Next seo test with react testing library
我正在嘗試測試我的 SEO 組件,它看起來像這樣:
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",
...
我的測試是這樣的:
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"))
})
})
但是測試失敗了:(看起來頭元素是空的)
我遇到了同樣的問題,但我在 GitHub 上找到了這個答案。
所以基本上你需要模擬next/head
,將document.head
傳遞給render
選項的容器屬性,最后訪問document
。
你的測試最終會是這樣的:
jest.mock('next/head', () => {
return {
__esModule: true,
default: ({ children }: { children: Array<React.ReactElement> }) => {
return <>{children}</>;
},
};
});
describe("Seo", () => {
it("should render the meta tags", () => {
const props = {
title: "title page",
excerpt: "string",
seo: {
title: "seo title",
description: "meta description",
},
heroImage: {
src: "url",
alt: "alt text",
width: 300,
height: 400,
},
}
render(<Seo {...props} />, { container: document.head })
expect(document.title).toBe("title page")
})
})
就我而言,我沒有使用getMeta
function 對其進行測試,但我相信它也會起作用。
在 JS 中
jest.mock('next/head', () => {
return {
__esModule: true,
default: ({ children }) => {
return children;
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.