繁体   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