查询一个带有jest和的简单按钮



我想测试我的组件,所以这里是:

import React from 'react';
import { useNavigate } from 'react-router-dom';
import '../styles/mainPageStyles.css';
const MainPage = (): React.ReactElement => {
const navigate = useNavigate();
const handleBeginQuiz = () => {
navigate('/quiz');
};
return (
<div className="mainPageContainer">
<div className="mainpageWrapper">
<h2 className="defaultFontSize">Welcome to the Trivia Challenge!</h2>
<p className="defaultFontSize">
You will be presented with 10 True or False questions.
</p>
<p className="defaultFontSize">Can you score 100%?</p>
<button
className="beginButton defaultFontSize"
onClick={handleBeginQuiz}
aria-label="BEGIN"
>
BEGIN
</button>
</div>
</div>
);
};
export default MainPage;

正如你所看到的,它只有一个功能,将我重定向到另一个页面,我结束了对按钮本身的click事件的测试,似乎我不能选择它,我总是得到这个错误:

Main Page Tests › On Begin Button Click
TestingLibraryElementError: Unable to find an element with the text: BEGIN. This could be because the 
text is broken up by multiple elements. In this case, you can provide a function for your text matcher to 
make your matcher more flexible.

,下面是我的尝试:


test('On Begin Button Click', () => {
const history = createMemoryHistory();
render(
<MemoryRouter initialEntries={[`/`]}>
<Routes>
<Route element={<MainPage />} />
</Routes>
</MemoryRouter>
);
// I have also tried getByText
const buttonElement = screen.getAllByText('BEGIN', { selector: 'button' });
// fireEvent.click(buttonElement);
// expect(history.location.pathname).toBe('/quiz');
});

尝试使用findByText代替getByText

最新更新