【问题标题】:Mocking next/head does not seem to do anything嘲笑下一个/头似乎没有做任何事情
【发布时间】:2022-03-09 16:36:36
【问题描述】:

我有一个使用 next/head 组件的 Seo 组件。我想测试这个 Seo 组件,但模拟 next/head 似乎什么也没做。我做错了吗?

import TestRenderer from 'react-test-renderer';
import Seo from '../Seo';

jest.mock(
  "next/head",
  () => function Head({ children }) {
    return children;
  },
);

it('should display seo', () => {
  const render = TestRenderer.create(
    <Seo />,
  );
  expect(render.toJSON()).toMatchSnapshot();
});
import Head from "next/head";

function Seo() {
  return (
    <Head>
      <title>Title SEO</title>
    </Head>
  );
}

【问题讨论】:

  • 你能澄清你所说的“嘲笑下一个/头似乎什么都不做”是什么意思吗?快照似乎具有 Seo 组件呈现的内容。你期待它做什么?
  • @juliomalves 因为 Head 组件将其内容注入到 document.head 中,所以模板中没有显示任何内容。这就是为什么我试图替换 Head 组件以便它简单地显示其内容。这就是我所说的“嘲笑它”。但它不起作用,快照保持为空。
  • 我明白了。使用上面的代码,模拟对我有用,我可以在快照中看到&lt;title&gt;Title SEO&lt;/title&gt;
  • 我的快照结果是:exports['should display seo 1'] = 'null'; 我正在使用"jest": "^27.4.7""next": "latest"(截至目前)。我正在测试新项目。你有什么主意吗?我不明白。

标签: reactjs jestjs next.js


【解决方案1】:

这对我有用(如果只使用 js,请删除 typescript)

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

【讨论】:

  • 它不起作用,请告诉我你正在使用的 next 和 jest 的版本吗?
  • "next": "12.0.10""jest": "^27.4.7"
【解决方案2】:

我不确定是否应该延迟测试以等待 DOM 操作结束。此外,document.head 可能需要作为container 提供。

it('should display seo', async () => {
  const render = TestRenderer.create(
    <Seo />, {container: document.head}
  );
  await waitFor(() => {
    expect(render.toJSON()).toMatchSnapshot();
  });
});

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2019-11-26
    • 2019-12-08
    • 1970-01-01
    • 2020-12-21
    • 2023-04-06
    相关资源
    最近更新 更多