我正在尝试对材质 ui 自动完成组件进行测试,我在此 example 中使用相同的组件,我尝试解决此 question 中的问题,但我没有找到解决方法。
我的测试代码如下,问题是我只得到我输入的城市,而不是第一个结果。我对其进行了一些测试,我认为它没有选择带有 ArrowDown
和 Enter
的可用选项。
// 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");
});
答案 0 :(得分:0)
如果我从你的链接中取出第一个组件到 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");
})
});
这将创建一个成功的测试。使用多选,它实际上会创建其他 html,因此我建议在下面进行调试。
还要注意我从渲染中进行调试,所以在任何时候我都可以看到 html 是什么(调用 debug())。这可以在您尝试实现某些目标的那一刻为您提供非常好的指示!我个人在监视模式下运行测试,并且可以从编辑器中设置断点,这对我有更多帮助。
编辑:当我尝试将 fireEvent.click(getAllByRole("option")[1]);
重命名为下面的部分时,它也能正常工作:
fireEvent.keyDown(input, { key: "ArrowDown" });
fireEvent.keyDown(input, { key: "Enter" });