[英]How to test conditionally rendered string using React testing library and jest
Hi I'm new to React testing library and need some assistance.嗨,我是 React 测试库的新手,需要一些帮助。 I would like to test the following code using React testing library to determine the text on the component conditionally either to be 'Active' or 'Inactive' based on the visibility prop which is a boolean:
我想使用 React 测试库测试以下代码,以根据 boolean 的可见性道具有条件地确定组件上的文本是“活动”还是“非活动”:
const SomeComponent = ({visibility}) => {
return (
<Badge>
{visibility ? 'Active' : 'Inactive'}
<Badge />
);
};
Any help would be greatly appreciated!任何帮助将不胜感激! Thank you!
谢谢!
Here is an example of tests you can write for your component:这是您可以为组件编写的测试示例:
import { render } from "@testing-library/react";
import SomeComponent from "./SomeComponent";
it("displays only active when visibility is true", () => {
const { queryByText } = render(<SomeComponent visibility={true} />);
expect(queryByText("Active")).toBeInTheDocument();
expect(queryByText("Inactive")).not.toBeInTheDocument();
});
it("displays only inactive when visibility is false", () => {
const { queryByText } = render(<SomeComponent visibility={false} />);
expect(queryByText("Active")).not.toBeInTheDocument();
expect(queryByText("Inactive")).toBeInTheDocument();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.