使用renderHook进行React Hook测试

时间:2020-10-09 21:18:47

标签: reactjs react-hooks react-testing-library use-state

我想使用@ testing-library / react-hooks中的renderHook测试组件的状态更新,这使我们可以像在react功能组件中一样渲染该钩子。 只是想知道,这仅适用于自定义钩子,因为在尝试测试组件时状态不会改变

it('test count update', () => {
    const { result } = renderHook(() => useState({ count: 0 }));
    const [state, setState] = result.current;
    const wrapper = mount(<ComponentToTest />);

    act(() => {
       wrapper.find('button').simulate('click');
    })
    expect(state).toBe({ count: 1 });
})

由于计数没有更新,仍然保持为0,因此出现错误

任何人都可以帮助

enter image description here

1 个答案:

答案 0 :(得分:1)

From the docs

渲染一个测试组件,该组件将在每次渲染时调用提供的回调,包括调用的任何挂钩。

renderHook用于测试挂钩本身,而不是使用该挂钩的组件。 renderHook本身提供测试组件;您无法通过渲染恰好使用自定义钩子的组件来测试钩子。

在您的情况下,您只是在测试useState,您可以绝对使用renderHook进行测试:

it('test count update', () => {
    const { result } = renderHook(() => useState({ count: 0 }));
    const [state, setState] = result.current;
    setState({count: state + 1});
    expect(state).toBe({ count: 1 });
})

但这似乎毫无意义;我们知道useState有用。

如果要测试使用useState(或任何挂钩)的组件,则需要渲染组件本身,并在渲染的组件中声明该挂钩的结果。例如

it('test count update', () => {
    const wrapper = mount(<ComponentToTest />);

    act(() => {
       wrapper.find('button').simulate('click');
    })
    // assuming the result is rendered in a span with a classname of 'result'
    expect(wrapper.find('span.result').text()).toBe('1');
})