React单元测试来查找组件中的元素



感谢您的帮助。在react中编写单元测试时,我被困住了。我需要检查操作按钮和链接按钮是否存在于组件中。这是我的组件代码。它正在渲染子组件并传递按钮作为渲染道具

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

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

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

输出显示了这一点错误:期望(收到).toBeTruthy ()

收到:假

按钮。请帮助。我已经尝试过浅和渲染

正确的方法是使用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);

最新更新