react-testing-library - 使用 React 测试库在嵌套组件中测试 data-testid 的最佳实践?

标签 react-testing-library

我正在尝试编写测试来检查我的应用程序是否正确呈现。在初始页面上,我添加了一个“开始”的数据测试标识。所以我的顶级测试检查初始组件是否已呈现。

import React from "react";
import { render } from "react-testing-library";
import App from "../App";

test("App - Check the choose form is rendered", () => {
  const wrapper = render(<App />);
  const start = wrapper.getByTestId("start");
  // console.log(start)
  // start.debug();
});

如果我 console.log(start) 我可以看到节点的所有属性。但是,如果我尝试 debug() 然后它会出错,说它不是一个函数。

我上面的测试似乎确实有效。如果我将 getByTestId 从 start 更改为其他任何内容,则会出错。但是我没有使用 expect 函数,所以我是否违反了最佳实践?

最佳答案

这个问题有两个部分-

Why console.log(start) works and why not start.debug()?

getByTestId 返回一个 HTMLElement。当您使用 console.log(start) 时,会记录 HTMLElement 详细信息。但是 HTMLElement 没有 debug 功能。相反,当您使用 render 渲染组件时,react-testing-library 为您提供了一个 debug 功能。因此,您不应使用 start.debug(),而应使用 wrapper.debug()

Because you don't have an expect function, is it a good practice to write such tests ?

我不确定什么是一个很好的答案,但我会告诉你我使用它的方式。使用 data-testid 获取元素有两种变体 - getByTestIdqueryByTestId。不同之处在于,如果未找到具有测试 ID 的元素,getByTestId 会抛出错误,而在这种情况下,queryByTestId 会返回 null。这意味着 getByTestId 本身就是对元素存在的断言。因此,如果您正在使用 getByTestId,那么使用另一个 expect 来检查是否找到元素将是多余的。如果我要断言元素的存在/不存在,我宁愿使用 queryByTestId。下面的示例-

test("App - Check the "Submit" button is rendered", () => {
 const { queryByTestId } = render(<App />)
 expect(queryByTestId('submit')).toBeTruthy()
});

我会在此类测试中使用 getByTestId,我知道元素存在并且我们期望元素的属性(而不是元素的存在/不存在)。下面的例子 -

test("App - Check the "Submit" button is disabled by default", () => {
 const { getByTestId } = render(<App />)
 expect(getByTestId('submit')).toHaveClass('disabled')
});

在上面的测试中,如果 getByTestId 找不到提交按钮,它会抛出错误而失败,并且不会执行 toHaveClass。这里我们不需要测试元素的存在/不存在,因为这个测试只关注按钮的“禁用”状态。

关于react-testing-library - 使用 React 测试库在嵌套组件中测试 data-testid 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52984394/

相关文章:

reactjs - 如何在 Jest 和测试/库中测试工具提示标题

javascript - 如何在 Jest 中模拟输入文本并按下 Enter 键

reactjs - 如何从屏幕上获取渲染的 HTML 元素,从 react 测试库?

reactjs - React-testing-library 为什么使用测试 id

react-testing-library - React 快照测试 - react-test-renderer 与 react-testing-library

react-testing-library - 如何组合复杂的选择器

react-testing-library - 如何模拟文件上传到 &lt;input type ="file"/> 元素?

javascript - React 测试库找不到 React-responsive 媒体查询中使用的任何组件

reactjs - 测试在按钮上呈现另一个组件单击 ReactJS

javascript - React 测试库 waitForElementToBeRemoved 无法正常工作