Ann*_*nna 10 setstate reactjs enzyme react-hooks
当我用酶测试类组件时,我可以wrapper.setState({})设置状态。当我用useState()钩子测试功能组件时,现在该怎么做?
例如,在我的组件中,我有:
const [mode, setMode] = useState("my value");
Run Code Online (Sandbox Code Playgroud)
我想改变mode测试范围
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.
You can find a great example in this blog post written by Kent C. Dodds.
Here's a code expert 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)
})
Run Code Online (Sandbox Code Playgroud)
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')
})
Run Code Online (Sandbox Code Playgroud)
小智 7
这是我发现的方法,我不是说这是对还是错。就我而言,代码块依赖于设置为特定值的状态。我会保留我对 React 测试的看法。
在您的测试文件中:调整您对反应库的导入
import * as React from 'react'
Run Code Online (Sandbox Code Playgroud)
然后在你的测试中监视 useState 并模拟它的实现
const stateSetter = jest.fn()
jest
.spyOn(React, 'useState')
//Simulate that mode state value was set to 'new mode value'
.mockImplementation(stateValue => [stateValue='new mode value', stateSetter])
Run Code Online (Sandbox Code Playgroud)
请注意,这种模拟 useState 将适用于为您的测试调用 useState 的所有实例,因此如果您正在查看多个状态值,它们都将被设置为“新模式值”。其他人可能会帮你解决这个问题。希望能帮助到你。
在测试文件的顶部,可以首先定义为:
import { useState } from 'react';
jest.mock('react', () => ({
...jest.requireActual('react'),
useState: jest.fn()
}));
const useStateMock: jest.Mock<typeof useState> = useState as never;
Run Code Online (Sandbox Code Playgroud)
之后,在每次测试时都可以使用想要测试的不同值:
const setValue = jest.fn();
useStateMock
.mockImplementation(() => ['value', setValue]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7674 次 |
| 最近记录: |