使用官方推荐的库来测react hook组件
最近写单元测试的时候遇见了一些问题,当我使用使用jest测React. useRef, React. useEffect时,总是测不到,
然后我去查阅了一下官方文档,它推荐了使用下面这个库
我来试了哈,还是不得行,于是根据这个库我在npm里头找到了相关的库,就是下面这个,专门用来测Hook的 @testing-library/react-hooks
下面开始示范我的用法,如有不对请稍加修改

1 import * as React from "react";
2 import {Chart} from "react-chartjs-2";
3 import {Chart as ChartJS, Title, Tooltip, Legend, CategoryScale, BarController, BarElement} from "chart.js";
4 import {IChartDataList} from "./IChartDataList";
5 import {ILinkPosition} from "./common";
6 import {ILink} from "./ILink";
7 import {IDatasetWithDetectionId} from "./IDatasetWithDetectionId";
8 import {ItemWithLoading} from "./ItemWithLoading";
9
10 // Register the elements to display ChartJs. Enables tree-shaking reducing bundle size.
11 // See https://www.chartjs.org/docs/latest/getting-started/integration.html#bundlers-webpack-rollup-etc
12 ChartJS.register(Title, Tooltip, Legend, CategoryScale, BarController, BarElement);
13
14 export interface ISum {
15 subscript: number;
16 totalReject: number[];
17 label: string;
18 sumOfTotalReject?: number;
19 }
20
21 export interface IBarChartProps {
22 /** The state of showing loading icon while sending request */
23 showLoading: boolean;
24 /** height of chart */
25 chartHeight: number;
26 /** current bar data */
27 itemData: IChartDataList;
28 /** sort data by label or total reject, if true, sort by total reject */
29 sortByReject: boolean;
30 }
31
32 export const BarChart: React.FC<IBarChartProps> = (props: IBarChartProps) => {
33 const chartRef = React.useRef<ChartJS>(null);
34
35 /**
36 * @returns options property or bar chart
37 */
38 const getOptionBarChart = (titleKey?: string) => {
39 return {
40 maintainAspectRatio: false,
41 scales: {
42 x: {
43 stacked: true,
44 },
45 y: {
46 stacked: true,
47 },
48 },
49 plugins: {
50 title: {
51 display: true,
52 text: titleKey,
53 },
54 },
55 };
56 };
57
58 /**
59 * use official function to update chart, more detail you can see
60 * 1. [update.html](https://www.chartjs.org/docs/latest/developers/updates.html)
61 * 2. [chartRef-demo](https://react-chartjs-2.netlify.app/examples/chart-ref/)
62 */
63 const updateChartData = (chart) => {
64 if (chart.data !== null && chart.data !== undefined) {
65 chart = handleSortByReject(chart);
66 chart.update();
67 }
68 };
69
70 React.useEffect(() => {
71 const chart = chartRef.current;
72 if (chart !== null) {
73 updateChartData(chart);
74 }
75 }, [props.sortByReject, props.itemData.chartData.labels, props.showLoading, props.chartHeight]);
76
77 return (
78 <>
79 {/* * before get response of backend, show loading
80 * if backend return empty list, show 'no data'
81 * otherwise, render bar chart */}
82 <ItemWithLoading
83 height={props.chartHeight}
84 showLoading={props.showLoading}
85 ele={
86 props.itemData.chartData !== undefined &&
87 props.itemData.chartData.labels &&
88 props.itemData.chartData.labels.length !== 0 &&
89 props.itemData.chartData.datasets.length !== 0 && (
90 /** about ref of bar chart, more detail you can see
91 * [chartRef-demo](https://react-chartjs-2.netlify.app/examples/chart-ref/)
92 */
93 <Chart
94 type="bar"
95 ref={chartRef}
96 height={props.chartHeight}
97 data={props.itemData.chartData}
98 options={getOptionBarChart(props.itemData.titleKey)}
99 />
100 )
101 }
102 />
103 </>
104 );
105 };
BarChart
这是我的组件ItemWithLoading
注意:(节省时间小tips, 可以不关注这个组件)

1 import * as React from "react";
2 import {AppContext} from "../app/IAppContext";
3 import {Loading} from "../app/Loading";
4 import "../public/style/datalight/ItemWithLoading.scss";
5
6 export interface IItemWithLoadingProps {
7 height: number;
8 /** if true, show loading icon */
9 showLoading: boolean;
10 ele?: JSX.Element | boolean;
11 }
12
13 /** render no data */
14 export const ItemWithLoading: React.FC<IItemWithLoadingProps> = (props: IItemWithLoadingProps) => (
15 // before render element, show loading
16 <AppContext.Consumer>
17 {(ctx) =>
18 props.showLoading ? (
19 <Loading />
20 ) : props.ele ? (
21 props.ele
22 ) : (
23 // if ele not available, show 'no data'
24 <div className="tes-datalight-noData" style={{height: props.height}}>
25 {ctx.translator.translate("tes_fe_gallery_filter_nodata")}
26 </div>
27 )
28 }
29 </AppContext.Consumer>
30 );
这是测试

1 import * as React from "react";
2 import * as TypeMoq from "typemoq";
3 import {describe, expect, it, jest} from "@jest/globals";
4 import {ActiveElement, ChartEvent} from "chart.js";
5 import {hotChartData, hotData, mcalMultiChartData, mxChartData, mxData} from "./panel2MockData";
6 import {create} from "react-test-renderer";
7 import {IChartDataList} from "../../datalight/IChartDataList";
8 import {ILinkPosition} from "../../datalight/common";
9 import {ILink} from "../../datalight/ILink";
10 import {BarChart, IBarChartProps} from "../../datalight/BarChart";
11 import {ItemWithLoading} from "../../datalight/ItemWithLoading";
12 import {Chart} from "react-chartjs-2";
13 import {renderHook} from "@testing-library/react-hooks";
14
15 // define props of bar chart
16 const barChartProps: IBarChartProps = {
17 showLoading: true,
18 chartHeight: 300,
19 itemData: mxData,
20 sortByReject: true,
21 };
22
23 /**
24 *
25 * @param height height of chart
26 * @param sortByReject true means sort by total reject. false means sort by label
27 * @returns render component with given property
28 */
29 const renderFrame = (height?: number, sortByReject = false, chartData?: IChartDataList, showLoading = false) => (
30 <BarChart
31 showLoading={showLoading ? showLoading : false}
32 chartHeight={height ? height : 320}
33 itemData={chartData ? chartData : hotData}
34 sortByReject={sortByReject}
35 />
36 );
37
38 describe("render bar chart", () => {
39 it("bar height depend on props 'chartHeight'", () => {
40 const chartHeight = 200;
41 const wrappers = create(renderFrame(chartHeight, false));
42 expect(wrappers.root.findByType(ItemWithLoading).props.height).toBe(chartHeight);
43 wrappers.unmount();
44 });
45
46 it("bar showLoading depend on props 'showLoading'", () => {
47 // render component with property 'showLoading' as true
48 const wrapper = create(renderFrame(undefined, undefined, undefined, true));
49 expect(wrapper.root.findByType(ItemWithLoading).props.showLoading).toBeTruthy();
50 wrapper.unmount();
51 });
52
53 it("when props data is empty", () => {
54 const emptyData: IChartDataList = {
55 titleKey: "empty list",
56 detectionArr: [],
57 chartData: {labels: [], datasets: []},
58 };
59 // render component with empty data
60 const frame = create(renderFrame(undefined, undefined, emptyData));
61 expect(frame.root.findByType(ItemWithLoading).props.ele).toBeFalsy();
62 frame.unmount();
63 });
64
65
66 it("when props 'sortByReject' is false, test render hot chart", () => {
67 const newRef = {
68 current: {
69 update: jest.fn(),
70 // hot data has one items
71 data: hotChartData,
72 },
73 };
74 jest.spyOn(React, "useRef").mockReturnValueOnce(newRef);
75 /** render hooks
76 * more detail you can see [react-hooks-testing](https://react-hooks-testing-library.com/)
77 */
78 renderHook(() => BarChart(barChartProps));
79 expect(newRef.current.update).toHaveBeenCalledTimes(1);
80 });
81 });
BarChart.test.tsx
使用官方推荐的库来测react hook组件的更多相关文章
- SVN库迁移整理方法----官方推荐方式
以下是subversion官方推荐的备份方式. 关闭所有运行的进程,并确认没有程序在访问存储库(如 httpd.svnserve 或本地用户在直接访问). 备份svn存储库 #压缩备份 svnadmi ...
- 【译】值得推荐的十大React Hook 库
十大React Hook库 原文地址:https://dev.to/bornfightcompany/top-10-react-hook-libraries-4065 原文作者:Juraj Pavlo ...
- 从零搭建react+ts组件库(封装antd)
为什么会有这样一篇文章?因为网上的教程/示例只说了怎么做,没有系统详细的介绍引入这些依赖.为什么要这样配置,甚至有些文章还是错的!迫于技术洁癖,我希望更多的开发小伙伴能够真正的理解一个项目搭建各个方面 ...
- beeshell —— 开源的 React Native 组件库
介绍 beeshell 是一个 React Native 应用的基础组件库,基于 0.53.3 版本,提供一整套开箱即用的高质量组件,包含 JavaScript(以下简称 JS)组件和复合组件(包含 ...
- Hystrix已经停止开发,官方推荐替代项目Resilience4j
随着微服务的流行,熔断作为其中一项很重要的技术也广为人知.当微服务的运行质量低于某个临界值时,启动熔断机制,暂停微服务调用一段时间,以保障后端的微服务不会因为持续过负荷而宕机.本文介绍了新一代熔断器R ...
- 使用.NET Core中创建Windows服务(一) - 使用官方推荐方式
原文:Creating Windows Services In .NET Core – Part 1 – The "Microsoft" Way 作者:Dotnet Core Tu ...
- EF框架访问access数据库入门(后附官方推荐“驱动”版本)
vs2017调试通过. 1.添加需要的provider,有点添加驱动的意思.右击项目,NUGET “浏览”,“JetEntityFrameworkProvider”,安装,如图 完成后配置文件(控制台 ...
- 使用.NET Core创建Windows服务(一) - 使用官方推荐方式
原文:使用.NET Core创建Windows服务(一) - 使用官方推荐方式 原文:Creating Windows Services In .NET Core – Part 1 – The &qu ...
- 一年时间,Pipenv就成为Python官方推荐的顶级工具?
Pipenv是Kenneth Reitz在一年多前创建的“面向程序员的Python开发工作流程”,现在已成为管理软件包依赖关系的Python官方推荐资源. Python软件包安装管理的简要历史 为了正 ...
- [Android Pro] Android 官方推荐 : DialogFragment 创建对话框
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/37815413 1. 概述 DialogFragment在android 3.0时 ...
随机推荐
- Linux中如何通过yum或者apt下载安装MySQL
一. yum mysql5.7以下 mysql5.7以上 Centos8 可以,但是需要重新配置文件 可以,但是需要重新配置文件 可以,但是需要重新配置文件 Centos7 可以直接yum,但是是 ...
- Docker MariaDB配置主从复制
编写主节点配置文件master.cnf: [client] # 默认字符集 default-character-set=utf8mb4 [mysqld] # 字符集 character-set-ser ...
- Python 创建数字列表
创建数字列表 用于存储数字集合,高效地处理数字列表 使用函数range() range(value1,value2),从指定的第一个值开始数,到达指定的第二个值后停止,输出不包含第二个值 使用rang ...
- 聚合短信PHP代码示例短信接口调用CURL方法
聚合的短信相信大家已经做多了吧,网上的代码看了下就是感觉太繁琐了,不过网上的也是比较好的,用的是post方法,更安全,因我们的项目是在服务器上请求,又绑定了白名单 ,所以弄了个简单点的自己用,参考如下 ...
- 麻了,一个操作把MySQL主从复制整崩了
前言 最近公司某项目上反馈mysql主从复制失败,被运维部门记了一次大过,影响到了项目的验收推进,那么究竟是什么原因导致的呢?而主从复制的原理又是什么呢?本文就对排查分析的过程做一个记录. 主从复制原 ...
- 2022-10-24:以下go语言代码输出什么?A:3 3;B:3 4;C:0 0;D:0 1。 package main func main() { m := make(map[int]int
2022-10-24:以下go语言代码输出什么?A:3 3:B:3 4:C:0 0:D:0 1. package main func main() { m := make(map[int]int, 3 ...
- 2021-05-12:给定一个数组arr,只能对arr中的一个子数组排序, 但是想让arr整体都有序。返回满足这一设定的子数组中,最短的是多长?
2021-05-12:给定一个数组arr,只能对arr中的一个子数组排序, 但是想让arr整体都有序.返回满足这一设定的子数组中,最短的是多长? 福大大 答案2021-05-12: 从左往右遍历,缓存 ...
- 2021-12-23:每日温度。 请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。 示例 1: 输
2021-12-23:每日温度. 请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度.如果气温在这之后都不会升高,请在该位置用 0 来代替. 示例 1: 输入 ...
- vue-admin-template包下载地址
https://gitee.com/panjiachen/vue-admin-template/ https://github.com/PanJiaChen/vue-admin-template
- 时间不等人,但 Moment.js 可以等你解决时间问题!
前言 一直以来,处理时间和日期的JavaScript库,选用的都是Moment.js.它的API清晰简单,使用方便灵巧,功能还特别齐全. 我是Moment.js的重度使用者.凡是遇到时间和日期的操作, ...