简体   繁体   中英

How to test conditionally rendered string using React testing library and jest

Hi I'm new to React testing library and need some assistance. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM