handleClick()是我想测试的函数。
this.state = {
expanded: {},
}
handleClick = (e) => {
const { dataset } = e.target
this.setState((prevState) => ({
expanded: {
...prevState.expanded,
[dataset.id]: !prevState.expanded[dataset.id],
},
}))}
handleClick函数和dataId作为一个道具传递给一个Icon子组件。
<Icon
icon={
this.state.expanded[this.props.id] === false ? "plus" : "minus"
}
size="sm"
dataId={this.props.id}
onClick={this.handleClick}
/>
handleClick()函数在图标被按下时被调用。
const Icon = props => {
const { icon, size, dataId = null, onClick = null } = props
return (
<i
className={`fa fa-${icon} fa-${size}`}
data-id={dataId}
onClick={onClick}
/>
)
}
这是我对handleClick()的测试案例。
it("should update state when handleClick is invoked", () => {
const mockExpanded = {}
mockExpanded[initialProps.id] = false
wrapper.setState({ expanded: mockExpanded })
const mockEvent = {
target: wrapper.find("Icon").dive().find("i").debug(), //need to pass target value as
an object
}
wrapper.instance().handleClick(mockEvent)
expect(wrapper.state().expanded[initialProps.id]).toBe(true) })
即使将mockEvent作为目标对象传递给handleClick(e),测试用例似乎也无法反构data-id属性。
TypeError: Cannot read property 'id' of undefined
27 | expanded: {
28 | ...prevState.expanded,
> 29 | [dataset.id]: !prevState.expanded[dataset.id],
| ^
30 | },
31 | }))
32 | }
请建议在jest测试用例中重构数据集的方法或测试handleClick(e)方法的适当方法。
解决方案:
it("should update state when handleClick is invoked", () => {
const mockExpanded = {}
mockExpanded[initialProps.id] = false
wrapper.setState({ expanded: mockExpanded })
const mockEvent = {
target: { dataset: { id: initialProps.id } },
}
wrapper.instance().handleClick(mockEvent)
expect(wrapper.state().expanded[initialProps.id]).toBe(true)
})