gpt4 book ai didi

reactjs - 如何使用 Jest 和 Enzyme 对包含 History.push 的 React 事件处理程序进行单元测试?

转载 作者:行者123 更新时间:2023-12-03 13:16:26 25 4
gpt4 key购买 nike

给定一个简单的组件:

export default class SearchForm extends Component {
constructor(props) {
super(props)
this.state = { query: '' }
}
onSubmit = (event) => {
event.preventDefault()
history.push(`/results/${this.state.query}`, { query: this.state.query })
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
value={this.state.query}
onChange={event => this.setState({ query: event.target.value })}
/>
<button>Search</button>
</form>
)
}
}

测试:

describe('SearchForm Component', () => {
it('should navigate to results/query when submitted', () => {
const wrapper = shallow(<SearchForm />)
...?
})
})

如何验证表单提交是否将用户带到具有正确查询值的下一页?

我尝试简单地模拟 onSubmit 处理程序并至少确认它已被调用,但这会导致由于 history.push 导致的安全错误。

const wrapper = shallow(<SearchForm />)
const mockedEvent = { target: {}, preventDefault: () => {} }
const spy = jest.spyOn(wrapper.instance(), 'onSubmit')
wrapper.find('form').simulate('submit', mockedEvent)
expect(spy).toHaveBeenCalled()

最佳答案

实际上很简单,当在测试中浅层渲染组件时,您可以将任何 Prop 传递给组件,如下所示:
const wrapper = shallow(<SearchForm history={historyMock} />)

顺便说一下,里面onSubmit ,你应该这样打电话 this.props.history.push(...) .

现在,要创建一个模拟(更多信息请参阅 documentation ),您可以在测试中这样编写:
const historyMock = { push: jest.fn() };

请记住,您实际上只是在 mock push history的方法对象,如果您在组件内使用更多方法并想要测试它们,您应该为每个测试的方法创建一个模拟。

然后,您需要断言 push模拟被正确调用。为此,您需要编写必要的断言:
expect(historyMock.push.mock.calls[0]).toEqual([ (url string), (state object) ]);
使用所需的(url string)(state object)待断言。

关于reactjs - 如何使用 Jest 和 Enzyme 对包含 History.push 的 React 事件处理程序进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50682726/

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