reactjs - 从笑话测试中访问 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>
</>
)
}
解决方案
这是不可能的,也不应该是,因为状态是一个实现细节。如果将状态重命名为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 函数。
推荐阅读
- python - Discord.py @client.event twitter 自动发布到特定频道
- google-apps-script - 如何在我的数据输入表单中只为 Google Sheet App Script 按钮创建一个必填字段?
- python - 有没有一种方法可以仅使用 pandas 将公式写入 .xlsx 文件,即不使用 xlsxwriter / openpyxl 之类的工具?
- schemaspy - Schemaspy 中的自定义输出生产者
- python - send_code_request (Telethon) 之后的无休止更新
- python - 是否可以在 Django 模型中的复选框或下拉列表下添加依赖文本和日期字段
- c# - 从 SQL 数据库中检索数据并使用动态创建的标签来显示 Ping 结果
- r - R包在两个版本号之间导入包?
- bash - 如果目录存储在变量中,那么在引用它时表示其子目录的正确方法是什么?
- node.js - 如何从 mongodb 获取和显示没有未定义值的所有值?