如何使用 React 测试库测试 material ui 自动完成 google 地图

How to test material ui autocomplete google map with react testing library

我正在尝试对 material ui 自动完成组件进行测试,我在此 example, I tried following the problem from this question 中使用相同的组件,但我没有找到如何解决它。

我的测试代码如下,问题是我只得到我在输入中输入的城市,而不是第一个结果。我稍微测试了一下,我认为它没有 select ArrowDownEnter 的可用选项。

// Autocomplete is the Autocomplete component from material ui
      test("Autocomplete Test", async () => {
        render(<Autocomplete />);
        const autocomplete = screen.getByTestId("autocomplete");
    
        const input = within(autocomplete).getByRole("textbox");
    
        autocomplete.click();
        autocomplete.focus();
    
        fireEvent.change(input, { target: { value: "london" } });
        fireEvent.keyDown(autocomplete, { key: "ArrowDown" });
        fireEvent.keyDown(autocomplete, { key: "Enter" });
    
      const inputt = within(autocomplete).getByRole("textbox");
    
      console.log(inputt.value);
    
      expect(inputt.value).toEqual("London");
    });

如果我从你的 link 中提取第一个组件到 material-ui,下面的测试实际上会成功。

组件:

      <Autocomplete
        data-testid="autocomplete"
        id="combo-box-demo"
        options={top100Films}
        getOptionLabel={(option) => option.title}
        style={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
      />

并测试:

describe("Foo", () => {
    it("can select the second item and proceed", async () => {

        const { debug, getAllByRole } = render(<Foo />);
        const autocomplete = screen.getByTestId("autocomplete");

        const input = within(autocomplete).getByRole("textbox");

        autocomplete.click();
        autocomplete.focus();

        fireEvent.change(input, { target: { value: "lo" } });

        // to be sure, or do `findAllByRole` which is also async
        await act(async () => {
            await new Promise(resolve => setTimeout(resolve, 0));
        });

        fireEvent.click(getAllByRole("option")[1]);

        expect(input.value).toEqual("The Lord of the Rings: The Fellowship of the Ring");
    })

});

这将创建一个成功的测试。使用 multi-select 它实际上会创建其他 html 因此我建议在下面进行调试。

另请注意,我从渲染器中进行了调试,因此在任何时候我都可以看到 html 是什么(调用 debug())。这可以为您在尝试实现某些目标时绘制的内容提供很好的指导!就个人而言,我 运行 在手表模式下进行测试,并且可以从编辑器中设置断点,这对我有很大帮助。

编辑:当我尝试将 fireEvent.click(getAllByRole("option")[1]); 重命名为下面的部分时,它也有效:

   fireEvent.keyDown(input, { key: "ArrowDown" });
   fireEvent.keyDown(input, { key: "Enter" });