登录
注册
开源
企业版
高校版
搜索
帮助中心
使用条款
关于我们
开源
企业版
高校版
私有云
模力方舟
我知道了
查看详情
登录
注册
Gitee Talk | 模力方舟 AI 应用开发沙龙第六站 · 8月23日 广州集结中!
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
取消
前往登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
Watch
不关注
关注所有动态
仅关注版本发行动态
关注但不提醒动态
22
Star
186
Fork
45
yanleweb
/
interview-question
代码
Issues
1065
Pull Requests
0
Wiki
统计
流水线
服务
质量分析
Jenkins for Gitee
腾讯云托管
腾讯云 Serverless
悬镜安全
阿里云 SAE
Codeblitz
SBOM
我知道了,不再自动展开
更新失败,请稍后重试!
移除标识
内容风险标识
本任务被
标识为内容中包含有代码安全 Bug 、隐私泄露等敏感信息,仓库外成员不可访问
如何 对 react 状态库进行单测, 比如 redux、recoil 等状态库【热度: 170】
待办的
#IBW9RH
yanleweb
拥有者
创建于
2025-03-25 23:42
**关键词**:前端单测模拟 react 状态 下面分别介绍如何对 Redux 和 Recoil 这两种常见的 React 状态库进行单元测试。 ### 测试 Redux Redux 是一个可预测的状态容器,主要由 actions、reducers 和 store 构成。单元测试时可分别对这些部分进行测试。 #### 1. 测试 Actions Actions 是用于描述状态变化的普通 JavaScript 对象。可以测试 action 创建函数是否返回正确的 action 对象。 ```javascript // actions.js export const increment = () => ({ type: "INCREMENT", }); // actions.test.js import { increment } from "./actions"; describe("increment action", () => { test("should return an action with type INCREMENT", () => { const action = increment(); expect(action.type).toBe("INCREMENT"); }); }); ``` #### 2. 测试 Reducers Reducers 是纯函数,接收当前状态和 action,返回新的状态。可以测试 reducer 在不同 action 下是否返回正确的状态。 ```javascript // reducer.js const initialState = { count: 0, }; const counterReducer = (state = initialState, action) => { switch (action.type) { case "INCREMENT": return { ...state, count: state.count + 1, }; default: return state; } }; export default counterReducer; // reducer.test.js import counterReducer from "./reducer"; describe("counterReducer", () => { test("should handle INCREMENT action", () => { const initialState = { count: 0 }; const action = { type: "INCREMENT" }; const newState = counterReducer(initialState, action); expect(newState.count).toBe(1); }); test("should return the same state for unknown action", () => { const initialState = { count: 0 }; const action = { type: "UNKNOWN_ACTION" }; const newState = counterReducer(initialState, action); expect(newState).toEqual(initialState); }); }); ``` #### 3. 测试 Connected Components 如果组件通过 `connect` 函数连接到 Redux store,可以使用 `enzyme` 或 `@testing-library/react` 来测试组件是否正确接收和使用 store 中的状态和 actions。 ```jsx // CounterComponent.jsx import React from "react"; import { connect } from "react-redux"; import { increment } from "./actions"; const CounterComponent = ({ count, increment }) => ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); const mapStateToProps = (state) => ({ count: state.count, }); const mapDispatchToProps = { increment, }; export default connect(mapStateToProps, mapDispatchToProps)(CounterComponent); // CounterComponent.test.js import React from "react"; import { render, fireEvent, screen } from "@testing-library/react"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; import CounterComponent from "./CounterComponent"; const mockStore = configureStore([]); describe("CounterComponent", () => { let store; beforeEach(() => { store = mockStore({ count: 0 }); }); test("should display the count from the store", () => { render( <Provider store={store}> <CounterComponent /> </Provider> ); const countElement = screen.getByText("Count: 0"); expect(countElement).toBeInTheDocument(); }); test("should dispatch increment action on button click", () => { render( <Provider store={store}> <CounterComponent /> </Provider> ); const incrementButton = screen.getByText("Increment"); fireEvent.click(incrementButton); const actions = store.getActions(); expect(actions).toEqual([{ type: "INCREMENT" }]); }); }); ``` ### 测试 Recoil Recoil 是一个用于管理 React 应用状态的库,主要包含 atoms(原子状态)和 selectors(派生状态)。 #### 1. 测试 Atoms Atoms 是 Recoil 中的基本状态单元。可以测试 atoms 的初始值是否正确。 ```javascript // atoms.js import { atom } from "recoil"; export const counterState = atom({ key: "counterState", default: 0, }); // atoms.test.js import { counterState } from "./atoms"; import { useRecoilValue } from "recoil"; import { renderHook } from "@testing-library/react-hooks"; describe("counterState", () => { test("should have an initial value of 0", () => { const { result } = renderHook(() => useRecoilValue(counterState)); expect(result.current).toBe(0); }); }); ``` #### 2. 测试 Selectors Selectors 是基于 atoms 或其他 selectors 派生出来的状态。可以测试 selectors 是否正确计算派生状态。 ```javascript // selectors.js import { atom, selector } from "recoil"; export const counterState = atom({ key: "counterState", default: 0, }); export const doubleCounterSelector = selector({ key: "doubleCounterSelector", get: ({ get }) => { const count = get(counterState); return count * 2; }, }); // selectors.test.js import { counterState, doubleCounterSelector } from "./selectors"; import { useRecoilValue, set } from "recoil"; import { renderHook } from "@testing-library/react-hooks"; describe("doubleCounterSelector", () => { test("should return double the counter value", () => { const { result } = renderHook(() => useRecoilValue(doubleCounterSelector)); expect(result.current).toBe(0); const { set } = renderHook(() => ({ set: (value) => useSetRecoilState(counterState)(value), })).result.current; set(5); const { result: newResult } = renderHook(() => useRecoilValue(doubleCounterSelector)); expect(newResult.current).toBe(10); }); }); ``` #### 3. 测试 Recoil 组件 可以测试使用 Recoil 状态的组件是否正确更新和渲染。 ```jsx // CounterComponent.jsx import React from "react"; import { useRecoilState } from "recoil"; import { counterState } from "./atoms"; const CounterComponent = () => { const [count, setCount] = useRecoilState(counterState); const increment = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }; export default CounterComponent; // CounterComponent.test.js import React from "react"; import { render, fireEvent, screen } from "@testing-library/react"; import { RecoilRoot } from "recoil"; import CounterComponent from "./CounterComponent"; describe("CounterComponent", () => { test("should display the count and increment on button click", () => { render( <RecoilRoot> <CounterComponent /> </RecoilRoot> ); const countElement = screen.getByText("Count: 0"); expect(countElement).toBeInTheDocument(); const incrementButton = screen.getByText("Increment"); fireEvent.click(incrementButton); const newCountElement = screen.getByText("Count: 1"); expect(newCountElement).toBeInTheDocument(); }); }); ``` 通过以上方法,可以对 Redux 和 Recoil 状态库进行有效的单元测试,确保状态管理逻辑的正确性。
**关键词**:前端单测模拟 react 状态 下面分别介绍如何对 Redux 和 Recoil 这两种常见的 React 状态库进行单元测试。 ### 测试 Redux Redux 是一个可预测的状态容器,主要由 actions、reducers 和 store 构成。单元测试时可分别对这些部分进行测试。 #### 1. 测试 Actions Actions 是用于描述状态变化的普通 JavaScript 对象。可以测试 action 创建函数是否返回正确的 action 对象。 ```javascript // actions.js export const increment = () => ({ type: "INCREMENT", }); // actions.test.js import { increment } from "./actions"; describe("increment action", () => { test("should return an action with type INCREMENT", () => { const action = increment(); expect(action.type).toBe("INCREMENT"); }); }); ``` #### 2. 测试 Reducers Reducers 是纯函数,接收当前状态和 action,返回新的状态。可以测试 reducer 在不同 action 下是否返回正确的状态。 ```javascript // reducer.js const initialState = { count: 0, }; const counterReducer = (state = initialState, action) => { switch (action.type) { case "INCREMENT": return { ...state, count: state.count + 1, }; default: return state; } }; export default counterReducer; // reducer.test.js import counterReducer from "./reducer"; describe("counterReducer", () => { test("should handle INCREMENT action", () => { const initialState = { count: 0 }; const action = { type: "INCREMENT" }; const newState = counterReducer(initialState, action); expect(newState.count).toBe(1); }); test("should return the same state for unknown action", () => { const initialState = { count: 0 }; const action = { type: "UNKNOWN_ACTION" }; const newState = counterReducer(initialState, action); expect(newState).toEqual(initialState); }); }); ``` #### 3. 测试 Connected Components 如果组件通过 `connect` 函数连接到 Redux store,可以使用 `enzyme` 或 `@testing-library/react` 来测试组件是否正确接收和使用 store 中的状态和 actions。 ```jsx // CounterComponent.jsx import React from "react"; import { connect } from "react-redux"; import { increment } from "./actions"; const CounterComponent = ({ count, increment }) => ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); const mapStateToProps = (state) => ({ count: state.count, }); const mapDispatchToProps = { increment, }; export default connect(mapStateToProps, mapDispatchToProps)(CounterComponent); // CounterComponent.test.js import React from "react"; import { render, fireEvent, screen } from "@testing-library/react"; import { Provider } from "react-redux"; import configureStore from "redux-mock-store"; import CounterComponent from "./CounterComponent"; const mockStore = configureStore([]); describe("CounterComponent", () => { let store; beforeEach(() => { store = mockStore({ count: 0 }); }); test("should display the count from the store", () => { render( <Provider store={store}> <CounterComponent /> </Provider> ); const countElement = screen.getByText("Count: 0"); expect(countElement).toBeInTheDocument(); }); test("should dispatch increment action on button click", () => { render( <Provider store={store}> <CounterComponent /> </Provider> ); const incrementButton = screen.getByText("Increment"); fireEvent.click(incrementButton); const actions = store.getActions(); expect(actions).toEqual([{ type: "INCREMENT" }]); }); }); ``` ### 测试 Recoil Recoil 是一个用于管理 React 应用状态的库,主要包含 atoms(原子状态)和 selectors(派生状态)。 #### 1. 测试 Atoms Atoms 是 Recoil 中的基本状态单元。可以测试 atoms 的初始值是否正确。 ```javascript // atoms.js import { atom } from "recoil"; export const counterState = atom({ key: "counterState", default: 0, }); // atoms.test.js import { counterState } from "./atoms"; import { useRecoilValue } from "recoil"; import { renderHook } from "@testing-library/react-hooks"; describe("counterState", () => { test("should have an initial value of 0", () => { const { result } = renderHook(() => useRecoilValue(counterState)); expect(result.current).toBe(0); }); }); ``` #### 2. 测试 Selectors Selectors 是基于 atoms 或其他 selectors 派生出来的状态。可以测试 selectors 是否正确计算派生状态。 ```javascript // selectors.js import { atom, selector } from "recoil"; export const counterState = atom({ key: "counterState", default: 0, }); export const doubleCounterSelector = selector({ key: "doubleCounterSelector", get: ({ get }) => { const count = get(counterState); return count * 2; }, }); // selectors.test.js import { counterState, doubleCounterSelector } from "./selectors"; import { useRecoilValue, set } from "recoil"; import { renderHook } from "@testing-library/react-hooks"; describe("doubleCounterSelector", () => { test("should return double the counter value", () => { const { result } = renderHook(() => useRecoilValue(doubleCounterSelector)); expect(result.current).toBe(0); const { set } = renderHook(() => ({ set: (value) => useSetRecoilState(counterState)(value), })).result.current; set(5); const { result: newResult } = renderHook(() => useRecoilValue(doubleCounterSelector)); expect(newResult.current).toBe(10); }); }); ``` #### 3. 测试 Recoil 组件 可以测试使用 Recoil 状态的组件是否正确更新和渲染。 ```jsx // CounterComponent.jsx import React from "react"; import { useRecoilState } from "recoil"; import { counterState } from "./atoms"; const CounterComponent = () => { const [count, setCount] = useRecoilState(counterState); const increment = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }; export default CounterComponent; // CounterComponent.test.js import React from "react"; import { render, fireEvent, screen } from "@testing-library/react"; import { RecoilRoot } from "recoil"; import CounterComponent from "./CounterComponent"; describe("CounterComponent", () => { test("should display the count and increment on button click", () => { render( <RecoilRoot> <CounterComponent /> </RecoilRoot> ); const countElement = screen.getByText("Count: 0"); expect(countElement).toBeInTheDocument(); const incrementButton = screen.getByText("Increment"); fireEvent.click(incrementButton); const newCountElement = screen.getByText("Count: 1"); expect(newCountElement).toBeInTheDocument(); }); }); ``` 通过以上方法,可以对 Redux 和 Recoil 状态库进行有效的单元测试,确保状态管理逻辑的正确性。
评论 (
0
)
登录
后才可以发表评论
状态
待办的
待办的
进行中
已完成
已关闭
负责人
未设置
标签
工程化
未设置
标签管理
里程碑
高
未关联里程碑
Pull Requests
未关联
未关联
关联的 Pull Requests 被合并后可能会关闭此 issue
分支
未关联
分支 (1)
标签 (64)
master
0.0.76
0.0.75
0.0.74
0.0.73
0.0.72
0.0.71
0.0.70
0.0.69
0.0.68
0.0.67
0.0.66
0.0.65
0.0.64
0.0.63
0.0.62
0.0.61
0.0.60
0.0.59
0.0.58
0.0.57
0.0.56
0.0.55
0.0.54
0.0.53
0.0.52
0.0.51
0.0.50
0.0.49
0.0.48
0.0.47
0.0.46
0.0.45
0.0.44
0.0.43
0.0.42
0.0.41
0.0.40
0.0.39
0.0.38
0.0.37
0.0.36
0.0.35
0.0.34
0.0.33
0.0.32
0.0.31
0.0.30
0.0.29
0.0.28
0.0.27
0.0.26
0.0.25
0.0.24
0.0.23
0.0.22
0.0.21
0.0.20
0.0.19
0.0.18
0.0.17
0.0.16
0.0.15
0.0.14
0.0.13
开始日期   -   截止日期
-
置顶选项
不置顶
置顶等级:高
置顶等级:中
置顶等级:低
优先级
不指定
严重
主要
次要
不重要
参与者(1)
TypeScript
1
https://gitee.com/yanleweb/interview-question.git
git@gitee.com:yanleweb/interview-question.git
yanleweb
interview-question
interview-question
点此查找更多帮助
搜索帮助
Git 命令在线学习
如何在 Gitee 导入 GitHub 仓库
Git 仓库基础操作
企业版和社区版功能对比
SSH 公钥设置
如何处理代码冲突
仓库体积过大,如何减小?
如何找回被删除的仓库数据
Gitee 产品配额说明
GitHub仓库快速导入Gitee及同步更新
什么是 Release(发行版)
将 PHP 项目自动发布到 packagist.org
评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册