首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试材料-使用jest的UI Textfield选择组件

测试材料-使用jest的UI Textfield选择组件
EN

Stack Overflow用户
提问于 2020-01-17 01:09:48
回答 2查看 1.9K关注 0票数 2

我正在试着为一个简单的Material-UI Textfield select component写一个测试。测试应该显示选择一个选项会触发相应的事件。

下面是组件

代码语言:javascript
复制
<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组件。到目前为止,我最好的方法是这样。

代码语言:javascript
复制
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)。我做错了什么?

EN

回答 2

Stack Overflow用户

发布于 2020-02-10 14:22:37

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

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

代码语言:javascript
复制
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")
票数 1
EN

Stack Overflow用户

发布于 2020-05-16 00:52:59

您可以利用@testing-library/reactfindAByDisplayValue方法

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59774662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档