【发布时间】:2018-09-11 02:22:43
【问题描述】:
所以我开始使用 Jest 和 Enzyme 设置对由 Material-UI 组件组成的 React 组件进行单元测试。到目前为止,每个事件模拟都运行良好,直到我遇到来自 Material-UI 的 Select 组件。 (下面有更多信息)
使用 create-react-app 引导项目并使用 material-ui-next。
依赖版本
- 反应:16.2.0
- React-Dom:16.2.0
- 反应脚本:1.1.1
- 材质界面:1.0.0-beta.35
- 开玩笑:安装包中的一个 (22.4.3)
- 酶:3.3.0
- 酶适配器反应 16:1.1.1
问题
我有一个名为 FiltersDesktop 的纯功能组件,由 Material-UI 表单字段组成。其中三个是 Select 组件,其他是来自 material-ui 的文本字段和日期选择器。
界面代码
<Collapse in={props.visible} className={'filters-container-desk'}>
<Grid container classes={{ typeContainer: "filter-container" }} id={'container-desk'}>
<Grid item lg={2} xl={2}>
<FormControl fullWidth={true}>
<InputLabel htmlFor="sources">Sources</InputLabel>
<Select
open
inputProps={{ name: 'sources-desk', id: 'sources-desk' }}
value={props.filters.source || ''}
onChange={(event) => props.updateFilter({ source: event.target.value })}
>
<MenuItem value=''>
<em>None</em>
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</Grid>
<Grid item lg={2} xl={2}>
...
</Grid>
... // More Grid components of similar structure as above
</Grid>
</Collapse>
当我尝试在文本字段组件上模拟更改事件时,它工作正常。以下是我为测试文本字段编写的代码:
TextField 测试代码
const props = {
updateFilter: jest.fn()
};
test(`updateFilter should get called on simulating text changes in domain`, () => {
const component = mount(<FiltersDesktop {...this.props} />);
component.find('#domain-desk').last().simulate('change', { target: { value: 'scoopwhoop.com' } });
expect(props.updateFilter).toHaveBeenCalled();
});
但是类似的东西不适用于 Select 组件。但是,当我通过接口实际与 Select 字段交互时,会调用更新函数。以下是我为测试Select编写的测试代码:
选择测试代码
const props = {
updateFilter: jest.fn()
};
test(`updateFilter should get called on simulating text changes in sources`, () => {
const component = mount(<FiltersDesktop {...this.props} />);
// Did not work
component.find('#sources-desk').last().simulate('change', { target: { value: 20 } });
// Did not work
component.find('Select').first().simulate('change', { taget: { value: 20 } });
// Did not work
component.find('#sources-desk').forEach(element => element.simulate('change', { taget: { value: 20 } }))
expect(props.updateFilter).toHaveBeenCalled();
});
由于某些原因,find 方法在上述所有情况下总是返回超过 1 个元素,因此我在适当的情况下使用 first、last 和 forEach。
请帮助我找出在模拟它时未在 Select 组件上触发更改事件的原因。
请放心,我至少花了一周时间阅读 Github 上的问题,尝试实施 Jest 和 Enzyme 的解决方案和测试指南。我确信我的测试设置很好,因为其他情况都可以正常工作。
如果您想准确查看源代码,那么here 是存储库的链接。对存储库的拉取请求也受到赞赏。如果您在存储库上,请不要忘记切换到 react-material 分支。
P.S - 不要笑,因为我最近才开始使用 React:P
【问题讨论】:
标签: reactjs material-ui enzyme jestjs react-dom