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

Best practice for testing for data-testid in a nested component with React Testing Library?

我正在尝试编写一个测试来检查我的应用程序是否正确呈现。在初始页面上,我添加了 "start" 的 data-testid。所以我的顶级测试检查初始组件是否已呈现。

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 returns 一个 HTML 元素。当您使用 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 returns 为 null。这意味着 getByTestId 本身就是对元素存在的断言。因此,如果您使用 getByTestId,让另一个 expect 检查是否找到元素将是多余的。如果我要断言元素的 presence/absence,我宁愿使用 queryByTestId。下面的示例 -

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

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

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

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