使用useState()挂钩测试功能组件时设置状态

使用useState()挂钩测试功能组件时设置状态,第1张

使用useState()挂钩测试功能组件时设置状态

使用挂钩状态时,您的测试必须忽略诸如状态之类的实现细节,以便对其进行正确测试。您仍然可以确保组件将正确的状态传递到其子级。

您可以在Kent C. Dodds撰写的这篇博客文章中找到一个很好的例子。

这是摘录的代码示例。

依赖状态执行细节的测试-

test('setOpenIndex sets the open index state properly', () => {  const wrapper = mount(<Accordion items={[]} />)  expect(wrapper.state('openIndex')).toBe(0)  wrapper.instance().setOpenIndex(1)  expect(wrapper.state('openIndex')).toBe(1)})

不依赖状态实现细节的测试-

test('counter increments the count', () => {  const {container} = render(<Counter />)  const button = container.firstChild  expect(button.textContent).toBe('0')  fireEvent.click(button)  expect(button.textContent).toBe('1')})


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5477287.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存