在下一个js HEAD组件中测试JSON ld脚本标记



我们的项目使用next-js。我们在下一个js标签中使用标签添加json+ld格式的结构化数据。

现在我们有条件地添加这个json-ld-script标记。

我们的页面.tsx

<Head>
<title>{"meta title"}</title>
<meta name="description" content="meta desc"} />
{ structuredData && <Script
nonce={nonce}
type="application/ld+json"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: structuredData }}
/>}
</Head>

现在,我正试图使用react测试库和jest来测试这种行为,并在下面的jest.mock("next/head"(的帮助下进行测试。

jest.mock('next/head', () => {
return {
__esModule: true,
default: ({ children }: { children: Array<React.ReactElement> }) => {
return <>{children}</>;
},
};
});
const {debug}
render(<OurPage />);
debug();

问题是渲染屏幕只有元";标题";以及";描述";标签和丢失的";脚本";应该存在的标签。

有人知道怎么解决这个问题吗?

您可以尝试将data-testid="ldjson"添加到脚本标记中。我在这里使用了script标签,而不是esint所说的nextjs/script组件。但这个脚本没有加载任何内容,所以无论如何,使用Script标签应该是可以的。

<script
data-testid="ldjson"
type="application/ld+json"
dangerouslySetInnerHTML={addJsonLd()}
/>

然后在你的测试中:

const script = screen.getByTestId("ldjson");
expect(script).toBeDefined();
expect(script).toHaveTextContent("your expected value");

看起来RTLdebug方法不呈现脚本。

最新更新