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

查看:116
本文介绍了使用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");

我想在我的内部更改模式测试

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天全站免登陆