Reputation: 11
I'm new to testing using Jest and need to simulate a click event. I have been able to select the element with enzyme css selectors and trigger the event but the test is still failing saying I haven't run the function.
Test:
it('test',() => {
const e = { target: {id:'X'} }
const click = jest.fn();
let wrapper = shallow(<GameBoard onClick={click}/>);
let test = wrapper.find("#gameBoard").childAt(0)
test.simulate('click',e)
expect(click).toHaveBeenCalledTimes(1)
})
Component :
import React, {Component} from 'react'
class GameBoard extends Component {
handleClick = (e) => {
this.props.turn
if (e.target.innerText === ''){
this.props.addToTotalMoves()
e.target.innerText = this.props.turn
this.props.updateActiveBoardArray(e.target.id)
this.props.changeTurn()
}
}
render(){
return (
<div id ='gameBoard'>
<div
id = '0'
className = 'boardTile'
onClick = {this.handleClick}
></div>
Upvotes: 1
Views: 2715
Reputation: 23763
looking at source of GameBoard
's handleClick
we can see it does not call this.props.onClick()
.
Instead it calls
this.props.updateActiveBoardArray(e.target.id)
this.props.changeTurn()
So you have to pass those props
in your test and check if they are called:
const e = { target: {id:'X'} }
const updateActiveBoardArray = jest.fn();
const changeTurn= jest.fn();
let wrapper = shallow(<GameBoard
updateActiveBoardArray={updateActiveBoardArray}
changeTurn={changeTurn}
/>);
let test = wrapper.find("#gameBoard").childAt(0).simulate('click', e);
expect(updateActiveBoardArray).toHaveBeenCalledTimes(1);
expect(updateActiveBoardArray).toHaveBeenCalledWith('X');
expect(changeTurn).toHaveBeenCalledTimes(1);
Upvotes: 2