gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:04:27 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com