React Testing Library无法检测到已存在的Filters标题问题求助
React Testing Library无法检测到已存在的Filters标题问题求助
我现在遇到一个棘手的问题:我想验证当所有组件完成渲染后,页面上是否存在"Filters"这个标题,但React Testing Library始终检测不到它,还直接抛出了错误。
我把相关代码和错误截图放在下面:
FilterBox.js
import React from 'react'; import './FiltersBox.css'; function FiltersBox({ onSortSelected, onCategorySelected }) { function sortByPrice(e) { onSortSelected(e.target.value); } function sortByCategory(e) { onCategorySelected(e.target.value); } return ( <div className='items_container-filter_box'> <h3 className='filter_box-title'>Filters</h3> <div className='filter_box-filters_container'> <div className='filter_box-filter filter_box-first_filter'> <h5>By Price:</h5> <div className='filter_box-select'> <select onChange={sortByPrice}> <option value='none'>-</option> <option value='ascending'>Ascending</option> <option value='descending'>Descending</option> </select> </div> </div> <div className='filter_box-filter filter_box-second_filter'> <h5>By Category:</h5> <div className='filter_box-select'> <select onChange={sortByCategory}> <option value='none'>-</option> <option value="men's clothing">Men's Clothing</option> <option value="women's clothing">Women's Clothing</option> <option value='jewelery'>Jewelery</option> <option value='electronics'>Electronics</option> </select> </div> </div> </div> </div> ); }
MainSection.test.js
import React from 'react'; import { render, screen } from '@testing-library/react'; import MainSection from './MainSection.js'; beforeAll(() => { render(<MainSection />); }); test('Check if renders the Search Bar', () => { const textInput = screen.getByTestId('text-input'); expect(textInput).toBeInTheDocument(); expect(textInput).toHaveAttribute('type', 'text'); expect(textInput).toHaveAttribute('placeholder', 'Search here!'); }); test('Check if renders the Filters Box', () => { const filterTitle = screen.getByText(/Filters/i); const filterLabelByPrice = screen.getByText(/by price:/i); const filterLabelByCategory = screen.getByText(/by category:/i); const filtersComboBoxes = screen.getAllByRole('combobox'); expect(filterTitle).toBeInTheDocument(); expect(filterLabelByPrice).toBeInTheDocument(); expect(filterLabelByCategory).toBeInTheDocument(); expect(filtersComboBoxes).toHaveLength(2); });
我试了各种办法都没能解决这个问题。
更新:
我尝试了@nbjorling提供的解决方案,现在好像能正常工作了?不过有点奇怪的是,虽然错误提示还在,但两个测试都显示通过了(变成绿色)。
备注:内容来源于stack exchange,提问作者Kosh
相关产品推荐
相关产品推荐

