gpt4 book ai didi

reactjs - Jest 和 React 测试库,如何测试元素是否隐藏?

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

我在 Hover 上显示了一个弹出框,我想用 Jest 和 React 测试库对其进行测试,以查看该元素是否默认隐藏。
当我手动测试时一切正常,而不是当我用 RTL 测试它时。
我尝试使用 not.toBeInTheDocument 和 not.toBeVisible 但似乎该元素始终存在于 DOM 中,我不知道如何将其从 DOM 中删除
JSX代码:

<label
htmlFor="terms_and_conditions"
className="terms_and_conditions_box"
>
I agree with{" "}
<span className="terms_and_conditions_text" style={{ color: "blue" }}>
Terms and conditions
</span>
<div className="pop_over">No ice cream will be delivered</div>
</label>
CSS代码:
.terms_and_conditions_text:hover + .pop_over {
display: block;
}

.pop_over {
background: rgb(199, 196, 196);
padding: 2rem;
width: 14rem;
border-radius: 15px;
position: absolute;
right: -18rem;
top: -2rem;
display: none;
}
测试代码:
test("popover responds to hover", () => {
render(<SummaryForm />);

//* popover initially is hidden
const nullPopover = screen.queryByText(/No ice cream will be delivered/i);
expect(nullPopover).not.toBeInTheDocument();
});

最佳答案

我已经复制了您的代码,对我而言,该测试不适用于 toBeInTheDocument ,但适用于 toBeVisible只要display: none在那儿。
这是我的测试文件的代码,第一个测试没有通过,第二个通过:

import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";
import SummaryForm from "./App";

describe("popover responds to hover", () => {
test("popover initially is hidden (test with toBeInTheDocument)", () => {
render(<SummaryForm />);
const nullPopover = screen.queryByText(/No ice cream will be delivered/i);
expect(nullPopover).not.toBeInTheDocument();
});

test("popover initially is hidden (test with toBeVisible)", () => {
render(<SummaryForm />);
const nullPopover = screen.queryByText(/No ice cream will be delivered/i);
expect(nullPopover).not.toBeVisible();
});
});
here is the codesandbox where you can see it in action .

关于reactjs - Jest 和 React 测试库,如何测试元素是否隐藏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67744440/

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