在React中测试事件冒泡

时间:2019-11-23 16:01:52

标签: javascript reactjs testing jestjs enzyme

是否可以在React中测试事件冒泡?

例如:

Class Foo extends React.Component {
    doSmth() {
        console.log('bubble');
    }

    render() {
        return (
            <div onClick={this.doSmth}>
                <Bar />
            </div>
        );
    }
}

我有一个父级和一个子级组件。在Bar组件中某处触发了Click事件。
如何测试doSmth是否在Foo组件中执行?
另外我不得不提到我不能使用上下文和道具,因为这是一个非常简化的版本。

2 个答案:

答案 0 :(得分: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;

这是您可以通过开玩笑的​​广告酶测试事件冒泡的方法。

https://codesandbox.io/s/flamboyant-babbage-tl8ub

处查看工作示例

注意:进入“测试”标签以运行所有测试。

希望可以澄清这一点!

答案 1 :(得分:0)

基于此线程,看来React Testing Library允许事件冒泡:https://github.com/testing-library/react-testing-library/issues/122

听起来fireEvent.click默认具有bubbles: true,因此您应该能够执行以下操作,即您要单击的组件(按钮?)的文本为“ Click me”:

const {queryByText} = render(<Foo />);
fireEvent.click(queryByText(‘Click me’));