handleClick() is the function that i am trying to test :
this.state = {
expanded: {},
}
handleClick = (e) => {
const { dataset } = e.target
this.setState((prevState) => ({
expanded: {
...prevState.expanded,
[dataset.id]: !prevState.expanded[dataset.id],
},
}))}
The handleClick function and dataId is passed as a prop to an Icon child component :
<Icon
icon={
this.state.expanded[this.props.id] === false ? "plus" : "minus"
}
size="sm"
dataId={this.props.id}
onClick={this.handleClick}
/>
The handleClick() function is invoked when icon is pressed :
const Icon = props => {
const { icon, size, dataId = null, onClick = null } = props
return (
<i
className={`fa fa-${icon} fa-${size}`}
data-id={dataId}
onClick={onClick}
/>
)
}
This is my Test case in jest for 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) })
Even after passing the mockEvent as target object to the handleClick(e) it seems, the test case is unable to destructure the data-id attribute :
TypeError: Cannot read property 'id' of undefined
27 | expanded: {
28 | ...prevState.expanded,
> 29 | [dataset.id]: !prevState.expanded[dataset.id],
| ^
30 | },
31 | }))
32 | }
Please suggest a way to destructure the dataset in jest test case or a proper way to test the handleClick(e) method.
Aucun commentaire:
Enregistrer un commentaire