简体   繁体   English

如何使用 React 测试库和 jest 测试条件渲染的字符串

[英]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.

相关问题 如何使用 Jest 和 React 测试库测试 className - How to test a className with the Jest and React testing library 如何使用 onClick 函数 Jest/React 测试库测试 React 组件 - How to test react component with onClick function Jest/React testing library 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 使用 JEST 和 React 测试库在 Onclick Function 中测试 API 调用 - Test API call in Onclick Function using JEST and React Testing Library 如何使用 Jest 测试库 React Native - How to test a library React Native using Jest 使用 react-testing-library 时如何测试组件是否使用正确的道具呈现? - How to test if a component is rendered with the right props when using react-testing-library? React 测试库 + Jest:如何测试接收数字然后对其进行格式化的组件 - React testing library + Jest: How to test a component that receives a number then format it 如何使用 React 测试库和 jest 测试 redux state 更新 - How to test redux state update with react testing library and jest 如何使用 jest 和 react 测试库为返回 function 的嵌套 jsx 编写测试用例 - how to write test case for nested jsx returning function using jest and react testing library 如何使用 React 测试库 + Jest 模拟测试函数 - How to mock functions for testing using the React Testing Library + Jest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM