我是React-Testing-Library的新手
我正在尝试测试内部具有条件渲染的组件。
是我的组件:
JButton mybutton = new JButton("ABC")
及其测试:
const ComponentA = () => {
const [isActive, setIsActive] = (false);
const toggle = () => {
setIsActive(!isActive)
}
return (
<>
<div>
<h1 onClick={toggle}>Title</h1>
</div>
{isActive && (<div className="some"><h4>SubTitle</h4></div>)}
</>
)
}
这里测试通过了,但我不想测试isActive案例。因此,如果使用className激活true div,则某些对象将渲染或不渲染。
我该怎么做?
答案 0 :(得分:2)
最好尽可能地在浏览器中测试组件的使用方式。在您的情况下,这意味着单击文本为“标题”的元素。 @testing-library/react
是使用fireEvent
的好方法。
import React from "react";
import { ComponentA } from "./";
import { render, screen, fireEvent } from "@testing-library/react";
import '@testing-library/jest-dom';
it("renders without crashing", () => {
render(
<ComponentA />
);
expect(screen.getByText("Title")).toBeInTheDocument();
// use queryBy* for checking existence,
// no element with text "Subtitle" should be on screen
expect(screen.queryByText("Subtitle")).toBe(null);
// Simulate clicking on "Title"
fireEvent.click(screen.getByText("Title"));
// Now "Subtitle" should be on screen
expect(screen.getByText("Subtitle")).toBeInTheDocument();
// Click again so that "Subtitle" disappears
fireEvent.click(screen.getByText("Title"));
// "Subtitle" should be gone
expect(screen.queryByText("Subtitle")).toBe(null);
// cleanup done automatically
});