import React from 'react';
import { mount } from 'enzyme';
import Foo from './Foo'
describe("Foo", () => {
it("should bubble the event up and call parent's handleClick", () => {
const handleClick = jest.spyOn(Foo.prototype, 'handleClick') //spy on handleClick function
const wrapper = mount(<Foo />);
wrapper.find('button').simulate('click'); //finding the button and simulating click
expect(handleClick).toHaveBeenCalledTimes(1) //verify function was called after click simulation
})
})
Foo.js
import React, { Component } from 'react';
import Bar from './Bar';
class Foo extends Component {
handleClick(){
console.log("bubbled")
}
render() {
return (
<div onClick={this.handleClick}>
<Bar />
</div>
);
}
}
export default Foo;
Bar.js
import React, { Component } from 'react';
class Bar extends Component {
render() {
return (
<button>Click me!</button>
);
}
}
export default Bar;
This is how you can test event bubbling with jest ad enzyme.
Check out a working example here https://codesandbox.io/s/flamboyant-babbage-tl8ub
Note : Go into the tests tab to run all tests.
Hope that clarifies it!