测试材料-UI 文本字段选择组件与开玩笑



我正在尝试为一个简单的材料UI文本字段选择组件编写测试。测试应显示选择选项会触发相应的事件。

这里是组件

<TextField
inputProps ={{"data-testid": "testId"}}
id="TextFieldId"
aria-label={"TextFieldAriaLabel"}
select
label="Files"
value={limit}
onChange={handleLimitChange}
SelectProps={{
native: true,
}}
variant="outlined"
>
{[{value: 5, label: "5"}, {value: 10, label: "10"}, {value: 15, label: "15"}].map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</TextField>

选择值"10"会触发以 10 作为输入参数的函数调用。

我用开玩笑来写测试。我想单击选择组件以打开下拉列表。然后我想点击其中一个选项。为了证明事件被触发,我检查是否使用正确的参数调用了相关函数。 这听起来很简单,但我遇到了很多问题。大多数问题都与找不到元素有关,因为材料 ui 嵌套了不同的 html 组件。到目前为止,我最好的方法看起来像这样。

testObject.renderResult.getByTestId('testId').click();
testObject.rerender();
jest.runAllTimers();
const dropdown = testObject.renderResult.getByTestId('testId');
within(dropdown).getByText('10').click();
testObject.rerender();
jest.runAllTimers();
expect(mostRecentImports).toHaveBeenCalledWith(10)

Jest 找到了元素,但测试失败了。组件保持默认值,显示值 5(而不是 10(。我做错了什么?

我的应用程序中也遇到了同样的问题。最后,我使用我在这里找到的这个解决方案解决了它:https://github.com/testing-library/react-testing-library/issues/322#issuecomment-581650108

编写一个简单的函数来打开选择菜单并选择所需的选项:

const selectMaterialUiSelectOption = (element, optionText) => {
// The the button that opens the dropdown, which is a sibling of the input
const selectButton = element.parentNode.querySelector('[role=button]');
// Open the select dropdown
UserEvent.click(selectButton);
// Get the dropdown element. We don't use getByRole() because it includes <select>s too.
const listbox = document.body.querySelector('ul[role=listbox]');
// Click the list item
const listItem = within(listbox).getByText(optionText);
UserEvent.click(listItem);
};
[... in your test]
selectMaterialUISelectOption(getByTestId('testId'), "10")

您可以使用findAByDisplayValue方法@testing-library/react

https://testing-library.com/docs/dom-testing-library/api-queries#bydisplayvalue

最新更新