反应单元测试以查找组件中的元素

React unit test to find the element in the component

感谢任何帮助。我对在 React 中编写单元测试感到困惑。我需要检查组件中是否存在操作按钮和 link 按钮。 这是我的组件代码。它正在渲染子组件并将按钮作为渲染道具传递

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

目前可以成功挂载组件,但找不到操作按钮和link按钮。下面是我的单元测试:

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

输出显示 错误:expect(received).toBeTruthy()

收到:错误

用于按钮。请帮忙。我已经尝试过 shallow 和 render

正确的方法是使用 toBeInTheDocument() 函数。

像这样:

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

因此,您需要通过 idclass 名称(如

)来查找特定按钮
 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

使用 expect(actual.children().props().actionButton).toEqual(content.actionButton);

解决