我有一个父组件,其中有一个handleClick,它作为道具传递给子组件。
parent.js
_handleClick = async (buttonName, id) => {
if(buttonName === 'yes'){
... some logic
}else{
... some logic
}
}
<Child
handleClick={(buttonName, id) => this._handleClick(buttonName, id)}
/>
现在我如何调用 _handleClick 并运行测试用例?我应该如何调用该方法?
我在下面尝试过,但它没有按预期工作,因为它是一个箭头函数并且需要两个参数。
测试.js
const wrapper = shallow(<parent />)
expect(wrapper.find('Child').length).toEqual(1)
wrapper.find('Child').prop('handleClick')
wrapper.find('Child').prop('handleClick')
是函数,所以你可以这样调用它:
wrapper.find('Child').prop('handleClick')( /* your args here */ );
这是一个简化的工作示例:
import { shallow } from 'enzyme';
import * as React from 'react';
const Child = () => (<div></div>);
class Parent extends React.Component {
constructor(...args) {
super(...args);
this.state = { val: 'initial' };
}
_handleClick = async (buttonName, id) => {
// ... await something ...
this.setState({ val: buttonName });
}
render() {
return (<Child handleClick={(buttonName, id) => this._handleClick(buttonName, id)} />);
}
}
test('click handler', async () => {
const wrapper = shallow(<Parent />);
expect(wrapper.find('Child').length).toEqual(1); // Success!
await wrapper.find('Child').prop('handleClick')('the button name'); // <= call the handler
expect(wrapper.state()).toEqual({ val: 'the button name' }); // Success!
});
嗯,您可能需要使用 mount 方法而不是shallow 来渲染父组件。这将渲染子元素,否则仅渲染占位符。然后,您可能希望通过单击按钮或任何触发子组件中的事件的方式来触发实际的单击事件。