【问题标题】:Testing next.js title using next/head with jest and react-testing-library giving false positives使用带有 jest 和 react-testing-library 的 next/head 测试 next.js 标题,给出误报
【发布时间】:2020-09-28 07:55:29
【问题描述】:

我已经开始在我的最新项目中使用 Next.js,我想对这些页面进行一些测试。 我创建了一个_document 文件,在其中设置了我想要使用的所有元标记,包括页面标题。

<html>
<InlineStylesHead />

<body>
    <Main />
    <NextScript />

    <Head>
     <title>testing title</title>
    </Head>
</body>

</html>

然后我设置我的测试来呈现这个页面(应该包括这个_document 作为它的一部分)

它按预期工作(包括 SSR)。

然后我尝试使用react-testing-libraryjest 对其进行测试

这是我的测试:

it('should render the title', () => {
      render(<Page />);
      waitFor(() => {
          expect(document.title).toEqual('test title');
      });
});

不幸的是,它给了我误报,而expect 块无论如何都给了真。 我也尝试直接在页面上设置Head,不幸的是,同样的问题。

您是否使用过任何其他技术来测试此类事情? 谢谢!

【问题讨论】:

    标签: reactjs jestjs next.js react-testing-library testing-library


    【解决方案1】:

    expect 没有给出true,它只是在测试中被忽略。 waitFor 由于其性质是异步的,应该等待以影响测试结果。

    应该是:

    it('should render the title', async () => {
          ...
          await waitFor(() => {
              expect(document.title).toEqual('test title');
          });
    });
    

    【讨论】:

    • 问题来了,我要么得到误报(只是尝试用任何其他替换“测试标题”,它会给你误报),或者它显示:
    • received value must be an HTMLElement or an SVGElement. Received has type: string Received has value: ""
    • 您对await waitFor 有误报吗?在 OP 中,它并不是真正的误报,断言只是发生在测试之外(如果测试运行时间足够长,它可能会显示未捕获的异常)。我不确定为什么received value must be an HTMLElement or an SVGElement 会在这里发生。 toEqual 不应该导致这个错误,除非它被修改过。请提供可以重现问题的stackoverflow.com/help/mcve。试试repl.it/languages/jest
    • 刚刚创建了一个 repl.it 测试;)
    猜你喜欢
    • 2021-02-11
    • 2021-05-25
    • 2020-03-22
    • 2020-05-14
    • 2021-02-28
    • 2019-07-08
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多