Тестирование React компонента Button с помощью React Testing Library или Jest
Стек технологий: Typescript, React, Jest, React Testing Library У меня есть компонент:
const Button: FunctionComponent<ButtonProps> = ({
size = 'default',
type = 'default',
htmlType = 'button',
icon,
children,
...otherProps
}) => {
let Component;
if (type === 'primary') {
Component = PrimaryButton;
} else if (type === 'outline') {
Component = OutlineButton;
} else if (type === 'danger') {
Component = DangerButton;
} else if (type === 'dark') {
Component = DarkButton;
} else {
Component = DefaultButton;
}
let layout: StyledButtonProps['layout'] = size;
if (icon) {
if (size !== 'large') {
layout = !!children ? 'medium' : 'icon';
}
}
return (
<Component type={htmlType} {...otherProps} layout={layout}>
{icon ? <Icon>{icon}</Icon> : null}
{children}
</Component>
);
};
Как мне протестировать, что в случае переданного свойства type='primary' отрисуется правильный компонент PrimaryButton?
Спасибо.
Ответы (1 шт):
Там нет ничего сложного. Пошаговое руководство.
- Рендерить компонент, который будем проверять.
- Отправить правильный атрибут.
- Проверить отрисовывается или нет.
Пример:
render(<Button type="primary" />);const primaryButton = screen.getByRole("button", { name: /primary/i });Если у вас там вместо тегаbuttonдругой тег или имя отличаются, то поменяйте на правильный.expect(primaryButton).toBeInTheDocument();Существование кнопки можно разными способами проверить. Если ваша кнопка содержит специфический клас, то можно через него проверять.expect(primaryButton).toHaveClass("primary");
Финальный код будет таким.
test("Render correct button", () => {
render(<Button type="primary" />);
const primaryButton = screen.getByRole("button", { name: /primary/i });
expect(primaryButton).toBeInTheDocument();
});