You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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&apos;s Clothing</option>
            <option value="women's clothing">Women&apos;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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 13:12:40