[React] Test friendly approach
React test Approach
2023-09-14 08:59:18 时间
Add functional function such as change state, this should have tests covered.
For example, in a component, there is a function call 'addBox':
onAddBox = () => { const newBox = { id : this.state.boxes.length, color : 'red' }; const boxes = addBox(this.state.boxes, newBox); this.setState({ boxes }); };
Here we use a function call 'addBox', this is written in a new file:
export const addBox = (boxes, newBox) => boxes.concat(newBox);
SO when need to use it, we need to import it to the component, not just write this function into component methods. Because if we make this function sprated from component methods, we are able to test it by just simply import this function to the test file.
import {addBox} from '../components/App/AppHelper'; const boxes = [ { id : 0, color : 'red' }, { id : 1, color : 'red' } ]; const newBox = { id: 2, color: 'green' }; test('Should be able to add new box', () => { const expected = [ { id : 0, color : 'red' }, { id : 1, color : 'red' }, { id: 2, color: 'green' } ]; const result = addBox(boxes, newBox); expect(result).toEqual(expected); }); test('addBox should be immutable', () => { const result = addBox(boxes, newBox); expect(result).not.toBe(boxes); });
Here has two test, one is to test 'addBox' should actually add a new box to the existing array. Second test is to make sure we don't mutatue origianl data.
相关文章
- 推荐! 使用react-cropper-pro实现图片裁切压缩上传
- 基于react的简单轻便的开源图片预览组件
- React + Redux 开启 HMR/Hot Loader
- React Error: Failed at the xxx@0.1.0 start script 'react-scripts start'.
- React:不要动,否则你会被炒鱿鱼
- 【Web技术】1445- 如何使用 Hooks 写出高质量的 React 和 Vue 组件?
- react的jsx和React.createElement是什么关系?面试常问_2023-02-27
- 前端一面常见react面试题(持续更新中)_2023-02-27
- 从源码角度看React-Hydrate原理_2023-03-01
- 前端react面试题指北
- react源码分析context
- react源码分析--深度理解React.Context
- React源码学习进阶篇(一)新版React如何调试源码?
- React源码学习进阶(六)completeWork究竟做了什么
- 从源码层面理解 React 是如何做 diff 的
- 在React中使用 react-router-dom 编程式路由导航【含V5.x、V6.x】
- 面试官:你是怎样进行react组件代码复用的1
- react源码中的生命周期和事件系统_2023-02-06
- 一个资深iOS开发者对于React Native的看法
- React 许可证虽严苛,但不必过度 react