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



我在Hover上显示了一个popover,我想用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,但只要有display: none,就可以使用toBeVisible

这是我的测试文件的代码,第一个测试没有通过,第二个通过:

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();
});
});

这里是代码沙盒,你可以在其中看到它的实际操作。

最新更新