代码之家  ›  专栏  ›  技术社区  ›  kyrolos magdy

用jest和

  •  0
  • kyrolos magdy  · 技术社区  · 3 年前

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

    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;
    

    正如你所见,它只有一个功能,可以将我重定向到另一个页面, 我结束了对按钮点击事件的测试, 似乎我无法选择它,我总是会遇到这样的错误:

    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');
      });
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   Khalfoun Mohamed El Mehdi    3 年前

    尝试使用 findByText 而不是 getByText