首页 > 解决方案 > 使用 useState() 钩子测试功能组件时设置状态

问题描述

当我用酶测试类组件时,我可以wrapper.setState({})设置状态。useState()当我用钩子测试功能组件时,我现在该怎么做?

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

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

我想改变mode我的测试

标签: reactjsenzymesetstatereact-hooks

解决方案


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

您可以在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')
})

推荐阅读