Is it possible to test event bubbling in React?
For example:
Class Foo extends React.Component {
doSmth() {
console.log('bubble');
}
render() {
return (
<div onClick={this.doSmth}>
<Bar />
</div>
);
}
}
I have a parent and a child components. Click event is fired somewhere in a Bar component.
How to test that doSmth was executed in a Foo component?
Also i have to mention that i can't use context and props, cause this is a very simplified version.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With