Jest单元测试(一)

Jest 简介

Jest是Facebook一套开源的 JavaScript 测试框架,它自动集成了断言、JSDom、覆盖率报告等测试工具。
他适用但不局限于使用以下技术的项目:Babel, TypeScript, Node, React, Angular, Vue

官网地址:https://jestjs.io/en/

Jest 安装

使用 yarn 安装 Jest︰

yarn add --dev jest

或 npm:

npm install --save-dev jest

注:Jest的文档统一使用yarn命令,不过使用npm也是可行的。 你可以在yarn的说明文档里看到yarn与npm之间的对比。

Jest 的基本使用

  1. 新建项目
jest
├── request.js
├── request.test.js
└── package.json

package

{"name": "jest","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "jest"},"keywords": [],"author": "","license": "ISC","devDependencies": {"jest": "^26.6.3"}
}
  1. 编写 request.js 文件
function sum(a, b) {return a + b;}
module.exports = sum;
  1. 编写测试 request.test.js 文件
const sum = require('./request.js');test('adds 1 + 2 to equal 3', () => {expect(sum(1, 2)).toBe(3);
});

将下面的配置部分添加到你的 package.json 里面:

{"scripts": {"test": "jest"}
}
  1. 执行测试用例
    最后,运行 yarn test 或 npm run test ,Jest将打印下面这个消息:
 PASS  ./request.test.js✓ adds 1 + 2 to equal 3 (5 ms)Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.845 s
Ran all test suites.
✨  Done in 3.29s.

生成 Jest 配置文件

全局安装Jest命令行:

yarn global add jest

或者

npm install jest --global

最后,运行 jest --init ,Jest将打印下面这个消息:


LiuJun-MacBook-Pro:jest liujun$ jest --initThe following questions will help Jest to create a suitable configuration for your project✔ Would you like to use Typescript for the configuration file? … no
✔ Choose the test environment that will be used for testing › node
✔ Do you want Jest to add coverage reports? … yes
✔ Which provider should be used to instrument code for coverage? › v8
✔ Automatically clear mock calls and instances between every test? … yes📝  Configuration file created at /Users/liujun/Documents/huayun/test/jest/jest.config.js

生成一个基础配置文件 jest.config.js

/** For a detailed explanation regarding each configuration property, visit:* https://jestjs.io/docs/en/configuration.html*/module.exports = {// Automatically clear mock calls and instances between every testclearMocks: true,// The directory where Jest should output its coverage filescoverageDirectory: "coverage",// An array of regexp pattern strings used to skip coverage collection// coveragePathIgnorePatterns: [//   "/node_modules/"// ],// Indicates which provider should be used to instrument code for coveragecoverageProvider: "v8",// A list of reporter names that Jest uses when writing coverage reports// coverageReporters: [//   "json",//   "text",//   "lcov",//   "clover"// ],// An object that configures minimum threshold enforcement for coverage results// coverageThreshold: undefined,// An array of directory names to be searched recursively up from the requiring module's location// moduleDirectories: [//   "node_modules"// ],// An array of file extensions your modules use// moduleFileExtensions: [//   "js",//   "json",//   "jsx",//   "ts",//   "tsx",//   "node"// ],// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module// moduleNameMapper: {},// A list of paths to directories that Jest should use to search for files in// roots: [//   "<rootDir>"// ],// The paths to modules that run some code to configure or set up the testing environment before each test// setupFiles: [],// A list of paths to snapshot serializer modules Jest should use for snapshot testing// snapshotSerializers: [],// The test environment that will be used for testingtestEnvironment: "node", // jest-environment-jsdom or node// The glob patterns Jest uses to detect test files// testMatch: [//   "**/__tests__/**/*.[jt]s?(x)",//   "**/?(*.)+(spec|test).[tj]s?(x)"// ]
};

jest.config.js 配置说明:https://jestjs.io/docs/zh-Hans/configuration

https://www.jianshu.com/p/2f00475ade2a

修改 jest.config.js 配置文件

例如,将覆盖率输出的路劲修改为:coverage-test

{coverageDirectory: "coverage-test",
}

然后添加一个生成覆盖率的脚本 test2

  "scripts": {"test": "jest","test2": "jest --coverage"},

最后执行脚本:yarn test2, 控制台打印如下,并且跟目录会生成 coverage-test 文件夹

LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coveragePASS  ./request.test.js✓ adds 1 + 2 to equal 3 (3 ms)(node:59600) ExperimentalWarning: The fs.promises API is experimental
------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |    87.5 |       50 |     100 |    87.5 |                   request.js |    87.5 |       50 |     100 |    87.5 | 7                 
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.824 s
Ran all test suites.
✨  Done in 3.62s.

Jest 配置 Babel

如果项目使用ES6的语法,要给Jest配置Babel

  1. 修改 request.js 文件
// ES6
export const sum = (a, b) => {return a + b;
}// function sum(a, b) {
//     return a + b;
// }
// module.exports = sum;
  1. 修改测试 request.test.js 文件
// ES6
import { sum } from './request.js'
// const sum = require('./request.js');test('adds 1 + 2 to equal 3', () => {expect(sum(1, 2)).toBe(3);
});
  1. 执行 yarn test , 会发现控制报错,提示需要配置Babel
LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coverageFAIL  ./request.test.js● Test suite failed to runJest encountered an unexpected tokenThis usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".Here's what you can do:• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.• If you need a custom transformation specify a "transform" option in your config.• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.You'll find more details and examples of these config options in the docs:https://jestjs.io/docs/en/configuration.htmlDetails:/Users/liujun/Documents/huayun/test/jest/request.test.js:1({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { sum } from './request.js'; // const sum = require('./request.js');^SyntaxError: Unexpected token {at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
  1. 配置Babel, 将ES6的语法转成ES5

如果需要使用 Babel,可以通过 yarn来安装所需的依赖。

yarn add --dev babel-jest @babel/core @babel/preset-env

可以在工程的根目录下创建一个babel.config.js文件用于配置与你当前Node版本兼容的Babel:

// babel.config.js
module.exports = {presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

Babel的配置取决于具体的项目使用场景 ,可以查阅 Babel官方文档来获取更多详细的信息。

  1. 最后在执行 yarn test2, 控制输出如下,测试通过
LiuJun-MacBook-Pro:jest liujun$ yarn test2
yarn run v1.13.0
$ jest --coveragePASS  ./request.test.js✓ adds 1 + 2 to equal 3 (7 ms)(node:60762) ExperimentalWarning: The fs.promises API is experimental
------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |    87.5 |       50 |     100 |    87.5 |                   request.js |    87.5 |       50 |     100 |    87.5 | 3                 
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.903 s
Ran all test suites.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/3384.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

对 Jenkins+ANT+Jmeter 接口测试的实践

目录 1、前言 2、框架与数据准备 3、脚本设计 4、整理测试报告 1、前言 JenkinsANTJMeter是一种常见的接口测试实践方案&#xff0c;可以实现自动化的接口测试和持续集成。Jenkins是一个流行的持续集成工具&#xff0c;ANT是一个构建工具&#xff0c;而JMeter是一个功能强大…

SPEC CPU 2006 1.2 D2000 ARM64 aarch64平台 docker 环境下的编译 宿主机测试

由于spec cpu 2006版本太老&#xff0c;现代操作系统gcc版本远高于gcc4.3&#xff0c;且tools也没有提供arm64架构程序文件&#xff0c;导致安装编译会报大量编译错误&#xff0c;难以适配。故采用docker方式尝试编译。 系统 rootyeqiang-greatwall:/home/yeqiang/Downloads#…

JS逆向系列之猿人学爬虫第18题-jsvmp - 洞察先机

文章目录 目标网址加密参数分析Python 实现往期逆向文章推荐目标网址 https://match.yuanrenxue.cn/match/18题目标着难度是困难级别,主要还是vmp保护的JS代码调试困难,理清逻辑就会变得简单了 加密参数分析 请求第一页时没有加密参数,从第二页开始,url会携带t和v两个参数…

240. 搜索二维矩阵 II

题目描述&#xff1a; 主要思路&#xff1a; 利用矩阵中的单调性进行搜索。 class Solution { public:bool searchMatrix(vector<vector<int>>& matrix, int target) {int nmatrix.size(),mmatrix[0].size();int in-1,j0;while(i>0&&j<m){if(m…

详解CPU的态

目录 1.CPU的工作过程 2.寄存器 3.CPU的上下文 4.系统调用 5.CPU的态 1.CPU的工作过程 CPU要执行的指令的地址存在寄存器中&#xff0c;指令存放在内存中&#xff0c;而CPU本质上就是一个去内存中根据地址取指令&#xff0c;然后执行指令的硬件。 举一个例子&#xff1a…

【蓝图】p27开关门互动实现

p27开关门互动实现 创建一个门 添加初学者内容包 拖拽一个门到场景中 添加一个碰撞 创建盒体触发器 左侧模式->基础->盒体触发器&#xff0c;拖拽到门上&#xff0c;调整大小 开关门互动实现 做一个开门互动 要把开门逻辑写在关卡蓝图里 门设置为可移动 打开关卡蓝…

link和@import的区别,性能优化

link和import的区别 两者都是外部引用CSS的方式&#xff0c;它们的区别如下&#xff1a; link是XHTML标签&#xff0c;除了加载CSS外&#xff0c;还可以定义RSS等其他事务&#xff1b;import属于CSS范畴&#xff0c;只能加载CSS。 link引用CSS时&#xff0c;在页面载入时同时加…

url解析与拼接工具UrlUtils

import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map;/*** 功能描述:url解析与拼接*/ public class UrlUtils {/*** 在给定的url后面拼接查询参数* param baseUrl url地址* param params 要拼接的查询参数map* return 拼接上params查…

SpringBoot整合knife4j

knife4j 文档地址&#xff1a;https://doc.xiaominfo.com/ knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。 Swagger介绍 前后端分离开发模式中&#xff0c;api文档是最好的沟通方式。 Swagger 是一个规范和完整的框架&#xff0c;用于生成、描述、调用和…

实用在线工具网站分享

一、bejson网站&#xff1a; 1.功能 1&#xff09;json工具 2&#xff09;编码/解码、加密/解密 3&#xff09;格式化工具 4&#xff09;网络相关工具 5&#xff09;前后端工具 6&#xff09;正则生成等其他 7&#xff09;文档处理 8&#xff09;图片处理 9&#xff09;文字处…

Docker中Mysql数据备份

Docker中Mysql数据备份 1.创建备份用户2.准备测试数据3.完全备份4.知识点解析 1.创建备份用户 百度过程中&#xff0c;有人说用最高权限root直接备份&#xff0c;不可取不安全&#xff0c;所以单独创建一个用于备份的用户 学习–去看–Mysql 备份所需要的权限 1.进入Mysql容器…

6.Hive系列之DML数据操作(二)

语句和Mysql、PgSQL都类似&#xff0c;简单过一遍 # 全表查询 select * from studen; # 列查询 select name, age from student; # 列别名 select name AS name1, age age1 from student; # 常用函数 count max min sum avg等 select avg(score) avg_score from student; # 限…

修复漏洞(一)离线升级Docker版本

前言 一般人最好用的修复漏洞的方式就是更新版本起因是使用的Docker版本被检测出来有一堆漏洞&#xff08;例如&#xff1a;Docker 操作系统命令注入漏洞(CVE-2019-5736)&#xff09;更新环境无法联网&#xff0c;只能通过下载二进制文件的形式进行安装 步骤 可先通过which …

基于单片机的智能窗帘智能晾衣架系统的设计与实现

功能介绍 以STM32单片机单片机作为主控系统&#xff1b;OLED液晶显示当前环境温湿度&#xff0c;光照强度&#xff0c;时间&#xff0c;开关状态等信息&#xff1b;雨滴传感器检测当前环境是否下雨&#xff0c;天气下雨检测&#xff0c;天气潮湿时自动收衣服&#xff1b;可以通…

RabbitMq(一)

一、基本概念、常见工作模式以及简单使用 MQ全称Message Queue (消息队列)&#xff0c;是在消息的传输过程中保存消息的容器。多用于分布式系统之间进行通信。 小结 MQ消息队列&#xff0c;存储消息的中间件分布式系统通信两种方式:直接远程调用和借助第三方完成间接通信发…

openGauss学习笔记-09 openGauss 简单数据管理-创建数据库

文章目录 openGauss学习笔记-09 openGauss 简单数据管理-创建数据库9.1 语法格式9.2 参数说明9.3 示例 openGauss学习笔记-09 openGauss 简单数据管理-创建数据库 数据库安装完成后&#xff0c;默认生成名称为postgres的数据库。您需要自己创建一个新的数据库。 9.1 语法格式…

低代码技术:提高效率降低成本的全新选择

一、前言 企业想要独立的应用程序&#xff0c;开发者在寻求更快速、更高效、更灵活的开发方法&#xff0c;以适应快速变化的市场需求。在这个背景下&#xff0c;低代码技术以提高效率降低成本的方式走进人们视野&#xff0c;成为了一种全新的应用程序开发方式。 二、相比传统的…

金融中的数学:概率分布(下)

上篇博客介绍了离散型概率分布&#xff0c;本篇博客介绍连续型概率分布。 1.连续型概率分布 连续型均匀分布&#xff08;Continuous Uniform distribution&#xff09;是一种描述在特定区间内取值均匀分布的概率分布。在该分布中&#xff0c;随机变量在给定区间内的取值概率密…

上门服务小程序|上门家政小程序开发

随着现代生活节奏的加快和人们对便利性的追求&#xff0c;上门家政服务逐渐成为了许多家庭的首选。然而&#xff0c;传统的家政服务存在着信息不透明、服务质量不稳定等问题&#xff0c;给用户带来了困扰。为了解决这些问题&#xff0c;上门家政小程序应运而生。上门家政小程序…

Jupyter入门使用教程

1 Jupyter Notebook与Jupyter Lab简介 Jupyter Notebook是一个开源的Web应用&#xff0c;在深度学习领域非常活跃。用户可以在这里创建和分享可执行代码、可视化结构和注释说明的文档。 Jupyter Notebook以网页的形式展现&#xff0c;用户可以在此网页中直接编辑代码、运行程…