3

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • Does this answer your question? [jsdom: dispatchEvent/addEventListener doesn't seem to work](https://stackoverflow.com/questions/36803733/jsdom-dispatchevent-addeventlistener-doesnt-seem-to-work) (`enzyme` uses `jsdom` under the hood) – skyboyer Nov 23 '19 at 16:45

2 Answers2

1
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!

kooskoos
  • 4,622
  • 1
  • 12
  • 29
0

Based on this thread, it looks like React Testing Library allows for event bubbling: https://github.com/testing-library/react-testing-library/issues/122

It sounds like fireEvent.click has bubbles: true by default, so you should be able to do something like this, where the component (button?) you’re clicking has the text “Click me”:

const {queryByText} = render(<Foo />);
fireEvent.click(queryByText(‘Click me’));
helloitsjoe
  • 6,264
  • 3
  • 19
  • 32