【问题标题】:React testing library - check the existence of empty divReact 测试库 - 检查是否存在空 div
【发布时间】:2019-10-09 13:30:21
【问题描述】:

我正在测试一个组件,如果 ItemLength = 1, render 返回 null

const { container, debug } = render(<MyComp ItemLength={1} />);

当我在测试中调用debug() 时,它显示<div />。如何检查组件在我的测试中返回一个空 div?

【问题讨论】:

  • getByText(container, (content, element) => element.tagName.toLowerCase() === 'div') 尝试使用 getByText 匹配元素 TagName

标签: reactjs react-testing-library


【解决方案1】:

由于您正在尝试测试空 div,因此您可以尝试测试它的一种方法是匹配节点(另一种可能的解决方案是渲染的节点数)

getByText(container, (content, element) => element.tagName.toLowerCase() === 'div')

【讨论】:

  • 不确定这将如何工作。传递 container 会引发错误,因为它需要 string
【解决方案2】:

你可以使用jest-dom's toBeEmpty:

const { container } = render(<MyComp ItemLength={1} />)
expect(container.firstChild).toBeEmpty()

【讨论】:

  • 看来这个 toBeEmpty 自 jest-dom 5.9.0 以来已被弃用。
  • 正如@TheTFo 所述,截至我在 2020 年底撰写本文时,此解决方案似乎无法正常工作。Karolis Grinkevičius's answer below 适合我。
  • 使用 toBeEmptyDOMElement 因为 toBeEmpty 已被弃用
【解决方案3】:

在不扩展 jest 期望的情况下,以下内容也应该可以工作:

const { container } = render(<MyComp ItemLength={1} />)
expect(container.firstChild).toBeNull();

更新:2020 年的新方式

import { screen } from '@testing-library/react';

...

render(<MyComp ItemLength={1} />);

const child = screen.queryByTestId('data-testid-attribute-value');

expect(child).not.toBeInTheDocument();

【讨论】:

  • 新方法要求你有一个 ID,但如果你测试的东西不存在,为什么会有一个测试 ID?
  • @Batman 它不一定是data-testid 属性。理想情况下,您应该通过与可访问性相关的属性来查询元素,例如screen.queryByRolescreen.queryByText 或记录在 here 的其他查询。
  • 是的,但是如果没有角色/文本/任何其他可查询的内容,您该怎么办?
  • @akerr 如果您没有任何特定的查询,您可以随时使用document.querySelector,例如document.querySelector('.yourClassName').
【解决方案4】:

toBeEmpty - 抛出警告,您必须改用toBeEmptyDOMElement

    const pageObject = cretePage(<UserResources />, appState);

    expect(pageObject.noContent).toBeInTheDocument();
    expect(pageObject.results).toBeEmptyDOMElement();

【讨论】:

    【解决方案5】:

    .toHaveLength(0) 也应该在没有 jest-dom 扩展的情况下工作

    const wrapper = render(<MyComp ItemLength={1}/>);
    expect(wrapper.container.innerHTML).toHaveLength(0);
    

    【讨论】:

      【解决方案6】:

      你可以使用 js-dom 的toBeEmptyDOMElement 方法。 https://github.com/testing-library/jest-dom#tobeemptydomelement

      在您可以使用toBeEmptyDOMElement 之前,您需要安装jest-dom 并设置jest。 https://github.com/testing-library/jest-dom#usage

      const { container } = render(<MyComp ItemLength={1} />)
      expect(container.firstChild).toBeEmptyDOMElement()
      

      注意:toBeEmpty 方法已被弃用,建议使用toBeEmptyDOMElement

      【讨论】:

      • 通过这种方法,我得到了TypeError: expect(...).toBeEmptyDOMElement is not a function
      • @Hiroki 您需要先安装 jest-dom 才能使用它。更新答案以包括那个。yarn add --dev @testing-library/jest-dom
      猜你喜欢
      • 1970-01-01
      • 2011-10-05
      • 2019-08-03
      • 1970-01-01
      • 2021-07-14
      • 2016-02-24
      相关资源
      最近更新 更多