reactjs - 使用 useState() 钩子测试功能组件时设置状态
问题描述
当我用酶测试类组件时,我可以wrapper.setState({})
设置状态。useState()
当我用钩子测试功能组件时,我现在该怎么做?
例如在我的组件中,我有:
const [mode, setMode] = useState("my value");
我想改变mode
我的测试
解决方案
当使用来自钩子的状态时,您的测试必须忽略状态等实现细节才能正确测试它。您仍然可以确保组件将正确的状态传递给其子级。
您可以在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')
})
推荐阅读
- scala - 如何在 spark scala 中对两个数据帧进行操作
- c# - 用于对字段分配进行排序的 Visual Studio 扩展
- javascript - 使用 AJAX 请求生成 PDF
- sql - 将 Select 语句合并到 Update 语句中
- java - Selenium:比较复选框中的两个字符串数组
- scala - scala中的异步REST调用
- freemarker - 标签中的变量 - Freemarker
- javascript - 居中 Facebook“发送到 Messenger”按钮和文本
- assembly - 如何将标签推送到可重定位共享库中的堆栈中,其对象应使用-fPIC编译?
- c - 我的 sscanf 格式有什么问题