我正在试着为一个简单的Material-UI Textfield select component写一个测试。测试应该显示选择一个选项会触发相应的事件。
下面是组件
<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作为输入参数的函数调用。
我使用jest来编写测试。我想要单击选择组件以打开下拉列表。然后,我想单击其中一个选项。为了证明事件已被触发,我检查是否使用正确的参数调用了相关函数。这听起来很简单,但我遇到了很多问题。大多数问题都与找不到元素有关,因为material 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)。我做错了什么?
发布于 2020-02-10 14:22:37
我在我的应用中也遇到了同样的问题。最后,我使用这里找到的解决方案解决了这个问题:https://github.com/testing-library/react-testing-library/issues/322#issuecomment-581650108
编写一个简单的函数,打开select菜单并选择所需的选项:
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")发布于 2020-05-16 00:52:59
您可以利用@testing-library/react的findAByDisplayValue方法
https://testing-library.com/docs/dom-testing-library/api-queries#bydisplayvalue
https://stackoverflow.com/questions/59774662
复制相似问题