I\'m trying to write a simple test for a simple React component, and I want to use Jest to confirm that a function has been called when I simulate a click with enzyme. Accor
In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
Welcome to React
To get started, edit src/App.js and save to reload.
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow( )
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
Welcome to React
To get started, edit src/App.js and save to reload.
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow( )
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})