#reactjs #antd #react-testing-library
#reactjs #antd #react-testing-library
Вопрос:
У меня есть выпадающий список ant-design, в котором отображается список при наведении курсора на элемент. Я хочу протестировать список внутри выпадающего меню. Я использую fireEvent.mouseOver(), но он не работает. screen.debug() не показывает меню. Как протестировать элементы наведения?
Заранее спасибо
Ответ №1:
Вот мой тестовый код. Важно использовать await и дождаться появления меню.
MyDropdown.tsx
import React from 'react'
import { Menu, Dropdown, Button } from 'antd';
const menu = (
<Menu data-testid="dropdown-menu">
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/">
1st menu item
</a>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">
2nd menu item
</a>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="http://www.tmall.com/">
3rd menu item
</a>
</Menu.Item>
</Menu>
);
export const MyDropdown: React.FC = () => {
return(
<Dropdown overlay={menu} placement="bottomLeft" arrow>
<Button>bottomLeft</Button>
</Dropdown>
)
}
MyDropdown.test.tsx
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { MyDropdown } from "./MyDropdown";
describe("<MyDropdown />", () => {
it("check dropdown menu item", async () => {
render(<MyDropdown />);
fireEvent.mouseOver(screen.getByText('bottomLeft'));
await waitFor(() => screen.getByTestId('dropdown-menu'))
expect(screen.getByText('1st menu item')).toBeInTheDocument()
expect(screen.getByText('2nd menu item')).toBeInTheDocument()
expect(screen.getByText('3rd menu item')).toBeInTheDocument()
});
});
Комментарии:
1. Спасибо @rokki. С async await это сработало отлично
2. Для прохождения теста мне пришлось использовать mouseEnter вместо mouseOver
Ответ №2:
Вот код для справки. Наведите курсор на условия и положения, всплывающее окно покажет / скроет
<SummaryForm.js >
import React, { useState } from 'react';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Popover from "react-bootstrap/Popover";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
export default function SummaryForm() {
const [tcChecked, setTcChecked] = useState(false);
const popover = (
<Popover id="popover-basic">
No ice cream will be delivered
</Popover>
);
const checkboxLabel = (
<span>
<OverlayTrigger overlay={popover} placement="right">
<span style={{ color: 'blue' }}> Terms and Conditions</span>
</OverlayTrigger>
</span>
) ;
return (
<Form>
<Form.Group controlId="terms-and-conditions">
<Form.Check
type="checkbox"
checked={tcChecked}
onChange={(e) => setTcChecked(e.target.checked)}
label={checkboxLabel}
/>
</Form.Group>
<Button variant="primary" type="submit" disabled={!tcChecked}>
Confirm order
</Button>
</Form>
);
}
<SummaryForm.test.js >
import {
render,
screen,
waitForElementToBeRemoved,
} from '@testing-library/react';
import SummaryForm from '../Form';
import userEvent from '@testing-library/user-event';
test('Initial conditions', () => {
render(<SummaryForm />);
const checkbox = screen.getByRole('checkbox', {
name: /terms and conditions/i,
});
expect(checkbox).not.toBeChecked();
const confirmButton = screen.getByRole('button', { name: /confirm order/i });
expect(confirmButton).toBeDisabled();
});
test('Checkbox enables button on first click and disables on second click', () => {
render(<SummaryForm />);
const checkbox = screen.getByRole('checkbox', {
name: /terms and conditions/i,
});
const confirmButton = screen.getByRole('button', { name: /confirm order/i });
userEvent.click(checkbox);
expect(confirmButton).toBeEnabled();
userEvent.click(checkbox);
expect(confirmButton).toBeDisabled();
});
test('popover responds to hover', async () => {
render(<SummaryForm />);
// popover starts out hidden
const nullPopover = screen.queryByText(
/No ice cream will be delivered/i
);
expect(nullPopover).not.toBeInTheDocument();
// popover appears upon mouseover of checkbox label
const termsAndConditions = screen.getByText(/terms and conditions/i);
userEvent.hover(termsAndConditions);
const popover = screen.queryByText(/No ice cream will be delivered/i);
expect(popover).toBeInTheDocument();
// popover disappears when we mouse out
userEvent.unhover(termsAndConditions);
await waitForElementToBeRemoved(() =>
screen.queryByText(/No ice cream will be delivered/i)
);
});