首页 > 解决方案 > 从笑话测试中访问 useState 值

问题描述

在基于类的组件中,我可以通过以下方式轻松访问状态:

const control = shallow(<Test />);
control.state()

对于像下面这样的基于钩子的组件,我如何count从我的测试中访问?

const Test = () => {
    const [count, setCount] = useState(0);

    return (
        <>
            <button onClick={() => setCount(count + 1)}>Count</button>
            <div>{count}</div>
        </>
    )
}

标签: reactjsjestjsenzyme

解决方案


这是不可能的,也不应该是,因为状态是一个实现细节。如果将状态重命名为myCount,组件仍然可以工作,但测试会失败。

备选方案 1:测试 DOM

但是,由于您渲染了计数,您可以简单地期望渲染正确的计数。

使用示例react-testing-library

import { render, fireEvent } from 'react-testing-library'

const rendered = render(<Test />)
rendered.getByText(0) // Test that 0 is present in the DOM
fireEvent.click(rendered.getByText('Count'))
rendered.getByText(0) // Test that 1 is present in the DOM

备选方案2:提取reducer中的状态逻辑,并测试reducer

如果您真的想单独测试状态更新,您可以useReducer使用 轻松测试 reducer jest,因为它是一个纯 JavaScript 函数。


推荐阅读