我正在尝试使用test-id属性测试React Bootstrap NavDropdown元素,但React测试库找不到数据test属性。
我的导航.tsx
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import NavDropdown from 'react-bootstrap/NavDropdown';
import LOGO from './logo.svg';
const MyNav = (): JSX.Element => (
<Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
<Navbar.Brand href="/">
<img src={LOGO} width="30" height="30" alt="React Bootstrap logo" />
BBS
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<NavDropdown
title="English"
id="navbarScrollingDropdown"
data-testid="en-boards"
>
<NavDropdown.Item href="#en-news" data-testid="en-news">
News
</NavDropdown.Item>
<NavDropdown.Item href="#en-sensitive-may">
Politics
</NavDropdown.Item>
</NavDropdown>
<NavDropdown title="日本語" id="navbarScrollingDropdown">
<NavDropdown.Item href="#ja-news">ニュース</NavDropdown.Item>
<NavDropdown.Item href="#ja-sensitive-may">政治</NavDropdown.Item>
</NavDropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
);
export default MyNav;
我的导航测试.tsx
import React from 'react';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyNav from './MyNav';
test('renders nav', async () => {
const user = userEvent.setup();
render(<MyNav />);
const navBarBrandEl = screen.getByText('BBS');
const navDropDownElEn = screen.getByText('English');
const navDropDownElJa = screen.getByText('日本語');
expect(navBarBrandEl).toBeInTheDocument();
expect(navDropDownElEn).toBeInTheDocument();
expect(navDropDownElJa).toBeInTheDocument();
const enBoards = screen.getByTestId('en-boards');
await user.click(enBoards);
const enNews = within(enBoards).getByTestId('en-news');
expect(enNews).toBeInTheDocument();
});
测试结果为
TestingLibraryElementError: Unable to find an element by: [data-testid="en-news"]
Ignored nodes: comments, script, style
<div
class="nav-item dropdown"
data-testid="en-boards"
>
<a
aria-expanded="false"
class="dropdown-toggle nav-link"
href="#"
id="navbarScrollingDropdown"
role="button"
tabindex="0"
>
English
</a>
</div>
18 | const enBoards = screen.getByTestId('en-boards');
19 | await user.click(enBoards);
> 20 | const enNews = within(enBoards).getByTestId('en-news');
| ^
21 |
22 | expect(enNews).toBeInTheDocument();
23 | });
at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:40:19)
at node_modules/@testing-library/dom/dist/query-helpers.js:90:38
at node_modules/@testing-library/dom/dist/query-helpers.js:62:17
at getByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:111:19)
at Object.<anonymous> (src/MyNav.test.tsx:20:35)
环境
- macOS 12.5
- 类型脚本4.8.4
- React18.2.0
- React引导2.5.0
- 测试库/React13.4.0
我尝试过这个issue的解决方案,但没有成功。谢谢你阅读。有人能解决吗?
1条答案
按热度按时间ctzwtxfj1#
您应该单击enBoards内部的按钮,而不是enBoard本身。
这是更正后的片段。