React Testing Library测试中PaginationList组件未渲染问题求助
测试React组件时PaginationList未渲染的问题
我正在使用React Testing Library对应用前端进行测试。OrgList组件负责渲染页面上的卡片列表,同时导入了PaginationList组件用于显示底部分页栏。
遇到的问题:测试中调用render方法渲染OrgList组件时,所有卡片组件都能正常渲染(在screen.debug()输出的HTML中可见),但PaginationList组件未被渲染,导致无法测试其与OrgList的联动功能。
相关代码片段
OrgList.tsx
import SuperDashListCard from 'components/SuperDashListCard/SuperDashListCard'; import PaginationList from 'components/PaginationList/PaginationList'; ... function OrgList(): JSX.Element { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); ... return ( <> ... <div className={styles.list_box}> {data && (rowsPerPage > 0 ? data.organizationsConnection.slice( page * rowsPerPage, page * rowsPerPage + rowsPerPage ) : data.organizationsConnection ).map( (datas: { _id: string; image: string; name: string; admins: any; members: any; createdAt: string; location: string | null; }) => { return ( <SuperDashListCard id={datas._id} key={datas._id} image={datas.image} admins={datas.admins} members={datas.members.length} createdDate={dayjs(parseInt(datas?.createdAt)).format( 'DD/MM/YYYY' )} orgName={datas.name} orgLocation={datas.location} /> ); } )} </div> <div> <table> <tbody> <tr> <PaginationList data-testid="pagination" count={data ? data.organizationsConnection.length : 0} rowsPerPage={rowsPerPage} page={page} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} /> </tr> </tbody> </table> </div> </div> ... </> ); } export default OrgList;
OrgList.test.ts
... import OrgList from './OrgList'; ... describe('OrgList Pagination Testing', () => { test('Default Case: Only first five organization details should be shown in the correct order', async () => { const { container } = render( <MockedProvider addTypename={false} mocks={MOCKS}> <BrowserRouter> <Provider store={store}> <I18nextProvider i18n={i18nForTest}> <OrgList /> </I18nextProvider> </Provider> </BrowserRouter> </MockedProvider> ); await wait(); expect(container.textContent).toMatch(organizationsConnection[0].name); expect(container.textContent).toMatch(organizationsConnection[4].name); expect(container.textContent).not.toMatch(organizationsConnection[5].name); screen.debug(undefined, Infinity); // 渲染后的HTML中没有分页组件 ... }); });
排查建议
- 确认异步渲染完成:测试中使用的
await wait()可能不足以等待数据和组件完全就绪,替换为waitFor并明确等待分页组件出现:await waitFor(() => expect(screen.getByTestId('pagination')).toBeInTheDocument()); - 检查Mock数据有效性:确保MOCKS中返回的
organizationsConnection长度大于rowsPerPage(即大于5),如果总条数小于等于每页条数,PaginationList可能因内部逻辑被隐藏。 - 查看PaginationList内部逻辑:检查该组件是否存在条件渲染规则,比如当
count <= rowsPerPage时不渲染分页栏。 - 验证props传递正确性:确认
data存在时,count参数被正确赋值为data.organizationsConnection.length,而非默认的0。
内容的提问来源于stack exchange,提问作者Eshaan Aggarwal
相关产品推荐
相关产品推荐

