【问题标题】:Test event bubbling in ReactReact 中的测试事件冒泡
【发布时间】:2019-11-23 16:01:52
【问题描述】:

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

例如:

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

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

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

【问题讨论】:

标签: javascript reactjs testing jestjs enzyme


【解决方案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

注意:进入测试选项卡运行所有测试。

希望能澄清一下!

【讨论】:

    【解决方案2】:

    基于这个线程,看起来 React 测试库允许事件冒泡:https://github.com/testing-library/react-testing-library/issues/122

    听起来fireEvent.click默认有bubbles: true,所以你应该可以做这样的事情,你点击的组件(按钮?)有文本“点击我”:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2015-08-12
      • 1970-01-01
      • 2015-12-10
      • 2011-10-20
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多