我有一个父组件,它保持所有状态,并将我的子组件呈现在路由器中。我将一个函数从父级传递给子级作为道具来处理按钮单击。
import React, {Component} from 'react';
import 'whatwg-fetch';
import arrayOfObjects from '../arrayOfObjects';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import ChildComponent from './ChildComponent';
class Parent extends Component {
constructor() {
super();
this.fetchObject = this.fetchObject.bind(this);
const tempmyObject = {};
this.state = {
myObject: tempmyObject
};
}
fetchObject(event) {
const that = this;
fetch(path)
....
that.setState(
{
myObject: newObject
});
....
event.preventDefault();
};
render() {
return (
<Router>
<div>
<Route exact path='/GetUserInfo'
render={(props) => (
<ChildComponent {...props}
fields={arrayOfObjects}
myObject={this.state.myObject}
onChange={(event) => this.fetchObject(event)}
buttonName='foo'
/>
)}
/>
</div>
</Router>
);
}
}
export default Parent ;
import ShowChildComponent from './ShowChildComponent';
class ChildComponent extends Component {
render() {
return (
<div>
<ShowChildComponent
fields={this.props.arrayOfObjects}
myObject={this.state.myObject}
buttonName={this.props.name}
onChange={this.props.onChange}
/>
</div>
);
}
}
export default ChildComponent;
我使用了来自酶的mount,我想测试它并在我的单元测试中模拟按钮点击,然后测试段落中更改的数据。
在此之前,我将所有状态保存在子组件中,如下所示:
import React, {Component} from 'react';
import 'whatwg-fetch';
import ShowChildComponent from './ShowChildComponent';
class ChildComponent extends Component {
constructor(props) {
super(props);
this.fetchData = this.fetchData.bind(this);
const tempmyObject = {};
this.state = {
myObject: tempmyObject
};
}
fetchData(event) {
const that = this;
fetch(this.props.path)
.....
that.setState(
{
myObject: myObject,
});
....
event.preventDefault();
};
render() {
return (
<div>
<ShowChildComponent
fields={this.props.arrayOfObjects}
myObject={this.state.myObject}
buttonName={this.props.name}
onChange={this.fetchData}
/>
</div>
);
}
}
export default ChildComponent;
我可以模拟一下点击。我的测试看起来像这样:
it('renders ChildComponent button click message', () => {
const wrapper = mount(<ChildComponent fields={arrayOfObjects}
myObject={myObject}
path={'/some/path'}
buttonName='foo'
/>);
const p = <p className='myParagraph' id={id}>{value}</p>;
wrapper.find('button.getData').simulate('click');
expect(wrapper.find(ShowChildComponent).containsMatchingElement(p)).toEqual(true);
});
重构后如何实现同样的目标?