用笑话和酶测试自定义反应方法



我正在尝试在反应组件中测试一种方法。该组件是一个表单,它应该测试当单击提交按钮时调用的handleSubmit()方法。我已经尝试了以下方法。

it('handlesSubmit when submit button is clicked', () => {
wrapper.find(Button).simulate('click');
expect(wrapper.instance().handleSubmit).toHaveBeenCalled();
})

这给出了一个错误jest.fn() value must be a mock function or spy.所以我尝试了这个:

it('handlesSubmit when submit button is clicked', () => {
const handleSubmit = jest.fn();
wrapper.find(Button).simulate('click');
expect(handleSubmit).toHaveBeenCalled();
})

此错误说Expected mock function to have been called

第一个块失败,因为wrapper.instance().handleSubmit不是一个开玩笑的模拟函数;它是类方法定义它的任何内容。

第二个块失败了,因为handleSubmit虽然是一个开玩笑的模拟函数,但根本没有绑定到你的包装器组件。它是一个局部变量。当您模拟单击时,它会再次调用实际实现。

为了完成你想做的事情,你必须做这样的事情

it('handlesSubmit when submit button is clicked', () => {
const handleSubmit = jest.fn();
WrapperComponent.prototype.handleSubmit = handleSubmit;
const wrapper = shallow(<WrapperComponent />);
wrapper.find(Button).simulate('click');
expect(handleSubmit).toHaveBeenCalled();
})

其中包装组件是你正在测试的组件。

以上应该有效,但有时你可以以更好的方式完成类似的事情。根据组件的实现,测试调用 handleSubmit 方法中的功能通常比调用 handleSubmit 方法本身更容易。例如,如果我的组件是这样的

class TestComponent extends React.Component {
constructor(props) {
super(props)
this.state = { clicked: false }
this.onClick = this.onClick.bind(this)
}
onClick() {
this.props.onClick()
this.setState({ clicked: true })
}
render() {
return (
<button onClick={ this.onClick }>
{ 'Click Me' }
</button>
)
}
}

我可以通过做来测试它

it('calls onClick props and sets clicked state to true when clicked', () => {
const onClick = jest.fn();
const testComp = shallow(<TestComponent onClick={ onClick } />);
wrapper.find('button').simulate('click');
expect(onClick).toHaveBeenCalled();
expect(testComp.state('clicked')).toBe(true)
})

我通常更喜欢这种类型的测试,因为我不必覆盖原型,而且它实际上是在测试点击触发我期望的逻辑。最初的测试实际上只包括我将this.handleSubmit作为onClick属性传递给按钮组件,仅此而已。

最新更新