使用 useState() 钩子测试功能组件时设置状态 [英] Set state when testing functional component with useState() hook

查看:37
本文介绍了使用 useState() 钩子测试功能组件时设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用酶测试类组件时,我可以执行 wrapper.setState({}) 来设置状态.当我使用 useState() 钩子测试功能组件时,我现在如何做同样的事情?

When I tested class component with enzyme I could do wrapper.setState({}) to set state. How can I do the same now, when I am testing function component with useState() hook?

例如在我的组件中,我有:

For example in my component I have:

const [mode, setMode] = useState("my value");

我想在我的测试中更改 mode

And I want to change mode inside my test

推荐答案

当使用来自钩子的状态时,您的测试必须忽略状态等实现细节,以便正确测试它.您仍然可以确保组件将正确的状态传递给其子组件.

When using state from hooks, your test must ignore implementation details like state in order to properly test it. You can still make sure the component passes the correct state into its children.

你可以在这个中找到一个很好的例子博文由 Kent C. Dodds 撰写.

You can find a great example in this blog post written by Kent C. Dodds.

这是一个带有代码示例的摘录.

Here's an excerpt from it with a code example.

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

Test that relies on state implementation details -

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 that does not rely on state implementation details -

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')
})

这篇关于使用 useState() 钩子测试功能组件时设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆