React unit test to find the element in the component

Viewed 536

any help is appreciated. I was bit stuck with writing unit test in react. I need to check if action button and link button exists in the component. here is my code for component. It is rendering child component and passing button as render props

export interface CloseableNotificationBannerProps {
    title?: string;
    message: string;
    variant: "default" ;
    icon: "info";
    actionButton?: React.ReactNode;
    showLinkButton: boolean;
}

export const CloseableNotificationBanner: React.FC<CloseableNotificationBannerProps> =
    ({
       title,
       message,
       variant,
       icon,
       actionButton,
       showLinkButton
     }) => {

  const [show, setShow] = useState(false); // extract into props to deafult it

  const handleClick = () => setShow(prevState => !prevState);

  return (
        show ?
          <BasicNotificationBanner
              title={title}
              message={message}
              variant={variant}
              icon={icon}
              actionButton={actionButton}
              closeButton={showLinkButton && <LinkButton
                  variant="transparent"
                  color="neutrals.dn40"
                  onClick={handleClick}>&times;</LinkButton>}
          /> : null
      );
};

For now It is able to mount the component successfully but unable to find action button and link button. Below is my unit test:

    // Given

      const content = {
          message: chance.string(),
          icon: chance.pickone(["info", "check_circle", "warning"]),
          variant: chance.pickone(["default", "information", "success", "error", "warning"]),
          actionButton: <Button>button</Button>,
          showLinkButton: true
      };
    // When
    const actual = mount(<CloseableNotificationBanner  content={content}/>);
    const button = actual.find(Button);
    // Then
    expect(actual.exists()).toBeTruthy();
    expect(button.exists()).toBeTruthy();

output shows that Error: expect(received).toBeTruthy()

Received: false

for button. Please help. I have tried wit both shallow and render

3 Answers

The right way to do this is to use the toBeInTheDocument() function.

Like this:

expect(actual).toBeInTheDocument();
expect(button).toBeInTheDocument();

So, you need find particular button by its id or by its class name like

 expect(actual.find('#actionButton').length).toBe(1); // if it has actionButton id

 expect(actual.find('.button-class').at(0).length).toBe(1); // if its has many buttons and all have button-class and its on first position

 expect(actual.find('button').length).toBe(2); // 2, if you have only two buttons

solved it using expect(actual.children().props().actionButton).toEqual(content.actionButton);

Related