簡體   English   中英

如何使用 react-testing-library 測試帶有動作重定向的表單

[英]How to test a form with action redirection using react-testing-library

我使用表單和我的 React 應用程序的輸入添加了一個搜索欄,我想檢查它是否重定向到正確的頁面。 我正在使用 react-testing-library 和 react-router-dom。

這是我的組件(簡化):

const SearchBar = () => (
  <form action={'/search'}>
    <input type="search" name="q" placeholder="search"></input>
  </form>
)

所以我編寫了這個測試來檢查當我在輸入中輸入內容時,我是否被重定向到 /search 頁面(這發生在我的瀏覽器中)。 我跟着https://testing-library.com/docs/example-react-router/想出了這個:

  it('redirects to search page', async () => {
    const history = createMemoryHistory();
    const header = render(
      <Router history={history}>
        <Switch>
          <Route exact path="/">
            <SearchBar />
          </Route>
          <Route path="/search">
            <div>this is the search page</div>
          </Route>
        </Switch>
      </Router>
    );

    const searchBar = header.getByPlaceholderText('search');
    fireEvent.change(searchBar, { target: { value: 'myQuery' } });
    fireEvent.submit(searchBar);
    expect(screen.getAllByText('this is the search page')).toBeInTheDocument();
  });

不幸的是,它失敗並出現以下錯誤:

    TestingLibraryElementError: Unable to find an element with the text: this is the search page. 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.

    <body>
      <div>
        <form
          action="/search"
        >
          <input
            name="q"
            placeholder="search"
            type="search"
          />
        </form>
      </div>
    </body>

      91 |     fireEvent.change(searchBar, { target: { value: 'myQuery' } });
      92 |     fireEvent.submit(searchBar);
    > 93 |     expect(screen.getAllByText('this is the search page')).toBeInTheDocument();
         |                   ^
      94 |   });
      95 | });
      96 |

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:92:38
      at getAllByText (node_modules/@testing-library/dom/dist/query-helpers.js:127:15)
      at Object.<anonymous> (src/components/Header/Header.test.tsx:93:19)

據我了解,我相信提交表單不會改變我的路由器的位置。

有沒有辦法在不更改我的代碼的情況下通過測試? 或者我應該忘記依賴formaction ,而是實現一個處理重定向的自定義onSubmit屬性 - 我可以更輕松地測試它?

謝謝:)

表單操作不使用 React Router DOM,而是使用本地方法

<form action={'/search'}>

如果你想為此使用 React Router,請考慮使用 React onSubmit處理程序。 然后,在與您的實際實現集成后,您的原始測試應該或多或少地工作。

const SearchBar = () => {
  const history = useHistory();

  const handleSubmit = (event) => {
    // Prevent default native behavior of submit
    event.preventDefault();
    // Push the new location to React Router DOM
    history.push("/search");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="search" name="q" placeholder="search"></input>
    </form>
  );
};

如果您不希望更改實現以使用路由器,我認為一個好的解決方案是測試action屬性是否正確而不測試本機行為,特別是因為很難測試非路由器導航更改(示例)並且表單提交沒有完全實現到 JSDOM 中。

it('has form action for the search page', () => {
  const history = createMemoryHistory();
  const header = render(
    <Router history={history}>
      <SearchBar />
    </Router>
  );

  const searchBar = header.getByPlaceholderText('search');
  expect(searchBar).toHaveAttribute('action', '/search');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM