Ric*_*ral 11 unit-testing callback reactjs jestjs enzyme
说我有以下应用程序:
class Child extends React.Component {
render() {
return <button onClick={this.handleChildOnClick}>{this.props.children}</button>;
}
handleChildOnClick() {
this.props.onChildClick('foo');
}
}
class Parent extends React.Component {
render() {
return <Child onChildClick={this.handleParentOnClick}>click me</Child>;
}
handleParentOnClick(text) {
this.props.onParentClick(12345);
}
}
class App extends React.Component {
render() {
return <Parent onParentClick={(num) => console.log(num)} />;
}
}
Run Code Online (Sandbox Code Playgroud)
我很难找到测试Parent组件的正确方法.在Child和App一个都没有问题,但Parent...
我的意思是,如何测试Child组件上的单击是否将调用Parent单击回调而不:
Child.Parent应该作为浅层渲染单独测试.Child也将进行单独测试,如果我进行了渲染渲染,我基本上是在Child两次测试点击回调.handleParentOnClick的Parent实例.我不应该依赖Parent于此的确切实施.如果我更改了回调函数的名称,测试将会中断并且很可能是误报.有第三种选择吗?
小智 14
在测试时Parent,您可以:
import { shallow } from 'enzyme';
import { stub } from 'sinon';
describe('<Parent/>', () => {
it('should handle a child click', () => {
const onParentClick = stub();
const wrapper = shallow(<Parent onParentClick={onParentClick} />);
wrapper.find("Child").prop('onChildClick')('foo');
expect(onParentClick.callCount).to.be.equal(1);
// You can also check if the 'foo' argument was passed to onParentClick
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5541 次 |
| 最近记录: |