簡體   English   中英

React 中的測試事件冒泡

[英]Test event bubbling in React

是否可以在 React 中測試事件冒泡?

例如:

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

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

我有一個父組件和一個子組件。 單擊事件在 Bar 組件中的某處觸發。
如何測試在 Foo 組件中執行了 doSmth?
另外我不得不提到我不能使用上下文和道具,因為這是一個非常簡化的版本。

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
    })

})

文件

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;

酒吧.js

import React, { Component } from 'react';

class Bar extends Component {
    render() {
        return (
            <button>Click me!</button>
        );
    }
}

export default Bar;

這是您如何使用 Jest 廣告酶測試事件冒泡的方法。

在此處查看一個工作示例https://codesandbox.io/s/flamboyant-babbage-tl8ub

注意:進入測試選項卡以運行所有測試。

希望能澄清一下!

基於這個線程,它看起來像 React 測試庫允許事件冒泡: https : //github.com/testing-library/react-testing-library/issues/122

聽起來fireEvent.clickbubbles: true默認情況下為bubbles: true ,所以你應該能夠做這樣的事情,你點擊的組件(按鈕?)有文本“點擊我”:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM