簡體   English   中英

react 測試庫 - 測試 antd 自動完成組件

[英]react testing library - test antd autocomplete component

我想測試 antd 自動完成功能,只需確保當用戶輸入某些內容時,從 BE 獲取數據后會出現下拉值。

我正在嘗試模擬它:

it('user got results while typing something', async () => {
    const { getByTestId } = render(<AutoComplete />);
    const searchInput = getByTestId('autosuggest-trigger')
        .querySelector('.ant-select-selection-search-input');

    fireEvent.focus(searchInput);
    fireEvent.change(searchInput, { target: { value: 'Alice' } });
    expect(searchInput.value).toBe('Alice'); // All is good so far..

    await waitFor(() => {
        expect(
            document.querySelector('.ant-select-dropdown'),
        ).not.toBeNull(); // FAILS
    });
});

順便說一句,我在我的真實應用程序中得到了結果,但在測試中不能這樣做。

出了什么問題,我該如何解決?

您應該嘗試在包含“Alice”的自動完成建議列表項上觸發點擊事件:

it('user got results while typing something', async () => {
  const { getByTestId } = render(<AutoComplete />);
  const searchInput = getByTestId('autosuggest-trigger')
    .querySelector('.ant-select-selection-search-input');

  // in my experience this is not needed
  fireEvent.focus(searchInput);

  // so autocomplete list is open, showing "Alice" option
  fireEvent.change(searchInput, { target: { value: 'Alice' } });
  expect(searchInput.value).toBe('Alice'); // All is good so far..

  // now click on the autocomplete list item
  // in some occasion, many HTML elements matched so I had to use getAllByText then pick to right one
  fireEvent.click(getByText("Alice"));

  await waitFor(() => {
    expect(
      document.querySelector('.ant-select-dropdown'),
    ).not.toBeNull(); // FAILS
  });
});

這並不理想,應該簡化。 如果您的 select 不可搜索,這不是一個選項。

另請參閱https://stackoverflow.com/a/61115234/2295549

暫無
暫無

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

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