关键词:
Jest 使用指南 - - tsx 组件篇
#jest
首先考虑一下,React 组件我们需要测试哪些东西呢?
- React 组件的 render 结果是一个组件树,并且整个树最终会被解析成一个纯粹由 HTML 元素构成的树形结构
- React 组件可以拥有 state,且 state 的变化会影响 render 结果
- React 组件可以拥有生命周期函数,这些生命周期函数会在特定时间点执行
这就是我们的测试一个 React 组件需要考虑的东西了
接下来我们来考虑一下怎么去测试,Jest 提供了一个基于快照的测试方式,每当你想要确保你的UI不会有意外的改变,快照测试是非常有用的工具。
这里主要讲一下 React 提供的 react-test-render
和 react-dom/test-utils
,
- 如果需要测试事件(如 click, change, blur 等),那么使用 react-dom/test-utils
- 其它时候使用更简单、灵活的 react-test-renderer
react 组件的单测
import React from "react";
const ShallowRender = () =>
return (
<div>
<p>1111</p>
<ul>
<li>2222</li>
<li>3333</li>
<li>4444</li>
<li>5555</li>
</ul>
</div>
);
;
export default ShallowRender;
React-test-render 的 ShallowRenderer
组件只会被 render 一层(children 中的 React 组件不会被 render)
我们可以看一下源码中 getRenderoutput
getRenderOutput()
return this._rendered;
接着我们再来看看 在 render 方法中对this._rendered
的赋值
if (shouldRender)
const prevDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = this._dispatcher;
try
// elementType could still be a ForwardRef if it was
// nested inside Memo.
if (elementType.$$typeof === ForwardRef)
if (!(typeof elementType.render === "function"))
throw Error(
`forwardRef requires a render function but was given $typeof elementType.render.`
);
this._rendered = elementType.render.call(
undefined,
element.props,
element.ref
);
else
this._rendered = elementType(element.props, this._context);
finally
ReactCurrentDispatcher.current = prevDispatcher;
可以看到 this._rendered 的值是elementType 的返回值,具体 elementType 干嘛可以自己看一下,我们可以看到这里只取了 element 的 type,这个 element就是我们传入的 组件,这里只取了这个组件的 type,并没有深入递归的去取 props 的 children。
import ShallowRenderer from "react-test-renderer/shallow";
import ShallowRender from "./shallowRende";
describe("react component", () =>
it("shallow render", () =>
const render = new ShallowRenderer();
render.render(<ShallowRender />);
const result = render.getRenderOutput();
console.log(result.props);
expect(result.type).toBe("div");
);
);
React-test-render 的 FullRender
import TestRenderer from "react-test-renderer";
import ShallowRender from "./shallowRende";
describe("full render test", () =>
it("full test", () =>
const testRender = TestRenderer.create(<ShallowRender />);
const testInstance = testRender.root;
expect(testInstance.findAll((node) => node.type === "li")).toHaveLength(
4
);
);
);
react hooks
对于 hooks 的单测一般使用的库是 @testing-library/react-hooks
,它提供了常用的方法有 renderHook
, act
renderHook: 渲染一个用于测试的组件,这个组件会调用包含 hook 的callback。
参数说明:
* callback (() => any) - 测试组件每次渲染时调用的方法。这个方法应该调用需要测试的 hook。
* options (object) - 配置对象。有以下配置项:
* initialProps (object) - 传递给callback函数的初始值
* wrapper (componenet) - pass a React Component as the wrapper option to have it rendered around the inner element. This is most useful for creating reusable custom render functions for common data providers
返回值:
* result (object)
* current (any) - callback函数返回的值
* error (Error) - callback函数抛出的错误。
* waitForNextUpdate (function) - 返回一个 Promise,它在下次组件渲染时结束。一般用于由于异步操作导致状态更新的情况。
* rerender (function([newProps])) - 重新渲染测试组件的方法。重新渲染测试组件时,会再次调用callback函数。如果指定了newProps,则会将newProps传递给callback。
* unmount (function()) - 卸载测试组件。一般用于触发useEffect hook 的清除动作。
Act: 帮我们调用一个方法
下面就以常见的 count 变化写一个 hooks
// useCounter.ts
import useState from "react";
const useCounter = () =>
const [count, setCount] = useState(0);
const addCount = () =>
setCount(count + 1);
;
const subCount = () =>
setCount(count - 1);
;
return count, addCount, subCount ;
;
export default useCounter;
他的单测试如下这样的
// useCounter.test.ts
import renderHook, act from "@testing-library/react-hooks";
import useCounter from "./useCounter";
describe("count hook", () =>
it("count hook test", () =>
const result = renderHook(() => useCounter());
act(() =>
result.current.addCount();
);
expect(result.current.count).toBe(1);
act(() =>
result.current.subCount();
);
expect(result.current.count).toBe(0);
);
);
对 Vue tsx 组件运行 Jest 测试
】对Vuetsx组件运行Jest测试【英文标题】:RunningJesttestsagainsVuetsxcomponents【发布时间】:2019-03-1920:50:45【问题描述】:我正在尝试创建简单的样板来创建Vuetsx组件,但在配置Jest测试tsx组件时遇到问题。如果有人已经解决了类似的... 查看详情
jest使用指南--基础篇(代码片段)
Jest使用指南--基础篇#jestJest基础Jest语法descriptionDescribe,一种用于包含一个或多个相关测试的Jest方法。每次在开始为功能编写新的测试套件时,都将其包装在describe块中。description('一组测试的名称',()=> //测试的方法... 查看详情
jest使用指南--mock篇(代码片段)
Jest使用指南--Mock篇#jestJestMock为什么会用到Mock?Mock能帮我们解决什么问题?在项目中,一个模块的方法内常常会去调用另外一个模块的方法。在单元测试中,我们可能并不需要关心内部调用的方法的执行过程和结... 查看详情
jest使用指南--ts文件篇(代码片段)
Jest使用指南--ts文件篇#jestts文件的单测ts文件主要是一些工具方法的使用,然后对于其中的工具方法进行单测,比对返回的数据结构,包括基础数据类型、对象、数组、函数异步方法这部分直接参考测试异步代码·Jest... 查看详情
jest使用指南--ts文件篇(代码片段)
Jest使用指南--ts文件篇#jestts文件的单测ts文件主要是一些工具方法的使用,然后对于其中的工具方法进行单测,比对返回的数据结构,包括基础数据类型、对象、数组、函数异步方法这部分直接参考测试异步代码·Jest... 查看详情
Jest 无法运行 .tsx 文件(CRA 2,酶)
...:2019-11-0515:12:18【问题描述】:我无法在我的tsCRA2项目中使用“npmtest”,因为jest无法处理.tsx。我遵循了这个[设置指南](https://thetrevorharmon.com/blog/configuring-jest-and-enzyme-in-cre 查看详情
jest使用指南--mock篇(代码片段)
Jest使用指南--Mock篇#jestJestMock为什么会用到Mock?Mock能帮我们解决什么问题?在项目中,一个模块的方法内常常会去调用另外一个模块的方法。在单元测试中,我们可能并不需要关心内部调用的方法的执行过程和结... 查看详情
jest使用指南--基础篇(代码片段)
Jest使用指南--基础篇#jestJest基础Jest语法descriptionDescribe,一种用于包含一个或多个相关测试的Jest方法。每次在开始为功能编写新的测试套件时,都将其包装在describe块中。description('一组测试的名称',()=> //测试的方法... 查看详情
vue开发实战实战篇#46:如何做好组件的单元测试(代码片段)
说明【Vue开发实战】学习笔记。配置jest.config.js文件https://v1.test-utils.vuejs.org/zh/installation/#%E7%94%A8-jest-%E6%B5%8B%E8%AF%95%E5%8D%95%E6%96%87%E4%BB%B6%E7%BB%84%E4%BB%B6module.exports=//preset:"@v 查看详情
jest+enzymereact组件测试实践(代码片段)
≈最近把组件测试接入到日常开发,提高了项目代码健壮性,可维护性。本人也从0到1收获了组件测试的经验。本文总结一下最近两周组件测试相关的研究,包括:Jest+Enzyme的基本介绍Jest+Enzyme的实践Jest原理... 查看详情
Jest 测试在 tsx 语法上失败
】Jest测试在tsx语法上失败【英文标题】:Jesttestfailsattsxsyntax【发布时间】:2020-09-0506:14:46【问题描述】:我目前正在对我的项目实施开玩笑测试。该项目由ts+tsx文件组成。以下是我的jest.config.js文件。module.exports=preset:"ts-jest",test... 查看详情
ts-jest 无法运行 tsx 测试文件,因为从模块的 js 文件“导入”
...【发布时间】:2020-02-1016:58:37【问题描述】:我正在尝试使用ts-jest运行tsx测试文件form.spec.tsx。form.spec.tsx导入ReactQuill编辑器和一些插件。 查看详情
Webpack 代码拆分使用 vueJs 组件中断 jest 导入
】Webpack代码拆分使用vueJs组件中断jest导入【英文标题】:WebpackcodesplittingbreaksjestimportwithvueJscomponents【发布时间】:2017-12-1420:14:58【问题描述】:Jest在尝试加载具有动态导入代码的vueJs组件时抛出错误。组件:<script>constModal=... 查看详情
jest+enzymereact组件测试实践(代码片段)
≈最近把组件测试接入到日常开发,提高了项目代码健壮性,可维护性。本人也从0到1收获了组件测试的经验。本文总结一下最近两周组件测试相关的研究,包括:Jest+Enzyme的基本介绍Jest+Enzyme的实践Jest原理... 查看详情
使用 Typescript(TSX 文件)将道具传递给 React 中的子组件
】使用Typescript(TSX文件)将道具传递给React中的子组件【英文标题】:PasspropstochildcomponentinReact,withTypescript(TSXfile)【发布时间】:2017-01-3111:39:37【问题描述】:我正在使用VS2013并将现有项目设置为使用React(0.14)和Typescript(1.8.5)。我... 查看详情
androidjetpack架构组件——lifecycle使用篇(代码片段)
概述Lifecycle是一个持有组件生命周期状态的class,并且允许其他组件来观察生命周期的变化。并不局限于Activity或者Fragment。我们只知道生命周期是由操作系统或者进程中运行的代码进行管理。而且生命周期是Android工作原理的... 查看详情
unity脚本篇-使用组件控制gameobject(代码片段)
在Unity编辑器中,可以使用Inspector更改GameObject的组件属性,还可以使用脚本修改组件属性b以操纵GameObjects。不过,不同之处在于脚本可以随着时间的推移组件改变属性的值,或者响应用户的输出。通过在适当的时... 查看详情
unity脚本篇-使用组件控制gameobject(代码片段)
在Unity编辑器中,可以使用Inspector更改GameObject的组件属性,还可以使用脚本修改组件属性b以操纵GameObjects。不过,不同之处在于脚本可以随着时间的推移组件改变属性的值,或者响应用户的输出。通过在适当的时... 查看详情