gpt4 book ai didi

javascript - 使用 Jest 测试 React 组件的方法

转载 作者:行者123 更新时间:2023-11-28 20:22:32 25 4
gpt4 key购买 nike

我有一个容器组件负责为子表单组件方法提供保存功能。我正在尝试使用 Jest & Enzyme(我想我需要 enzyme ?)来测试子组件是否触发从父组件传递的函数。这两种方法如下所示:

class Parent extends Component {
handleSave = (someData) => (
/* do some ajax with someData */
)
render() {
return(
<ChildComponent {...this.props} handleSave={this.handleSave} />
)
}
}

class ChildComponent extends Component {
render() {
<form onSubmit={this.props.handleSave}>
<button type="submit">Submit</button>
</form>
}
}

和测试:

import React from 'react'
import ParentContainer from '../src/ParentContainer'

describe('<ParentContainer />', () => {

it('Should fire handle save when PatientScheduler form saves', () => {
const component = mount( <ParentContainer />)
component.handleSave = jest.fn()
component.find('[type="submit"]').simulate('click')
expect(component.handleSave).toHaveBeenCalled()
})

})

我收到的失败消息是 Expected mock function to have been called.

我觉得我已经完成了 90%。这里出了什么问题?谢谢。

最佳答案

问题是模拟并没有真正触发点击事件,而是运行 wrapper.prop('click')()。形成文档:

Common Gotchas

Currently, event simulation for the shallow renderer does not propagate as one would normally expect in a real environment. As a result, one must call .simulate() on the actual node that has the event handler set.

Even though the name would imply this simulates an actual event, .simulate() will in fact target the component's prop based on the event you give it. For example, .simulate('click') will actually get the onClick prop and call it.

因此您可以运行 component.find('form').simulate('submit')component.find('form').prop('onSubmit')( )

关于javascript - 使用 Jest 测试 React 组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41063495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com