Man*_*tis 2 reactjs jestjs enzyme
我试图在反应组件中测试一个方法.该组件是一个表单,应该测试handleSubmit()方法在单击提交按钮时被调用.我试过以下.
it('handlesSubmit when submit button is clicked', () => {
wrapper.find(Button).simulate('click');
expect(wrapper.instance().handleSubmit).toHaveBeenCalled();
})
Run Code Online (Sandbox Code Playgroud)
这给了一个错误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();
})
Run Code Online (Sandbox Code Playgroud)
这个错误说 Expected mock function to have been called
第一个块失败,因为wrapper.instance().handleSubmit不是一个jest模拟函数; 它是类方法定义的任何东西.
第二个块失败,因为handleSubmit虽然是一个jest模拟函数,但根本不依赖于你的包装器组件.这是一个局部变量.当您模拟单击时,它再次调用实际的实现.
为了完成你想要做的事情,你必须做这样的事情
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();
})
Run Code Online (Sandbox Code Playgroud)
其中WrapperComponent是您正在测试的组件.
以上应该有效,但你有时可以以更好的方式完成类似的事情.根据组件的实现,通常更容易测试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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我可以通过这样做来测试它
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)
})
Run Code Online (Sandbox Code Playgroud)
我通常更喜欢这种类型的测试,因为我不必覆盖原型,它实际上是测试点击触发了我期望的逻辑.原始测试实际上只涵盖了我传递this.handleSubmit作为onClick prop的Button组件,仅此而已.
| 归档时间: |
|
| 查看次数: |
2512 次 |
| 最近记录: |