【问题标题】: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
注意:进入测试选项卡运行所有测试。
希望能澄清一下!