【自动化测试】Jest体验之旅

news2024/9/22 3:30:04

目录

简介

快速体验

配置文件

Jest CLI 选项

--watchAll

--watch

使用 ES6 模块


简介

Jest 是 Facebook 出品的一个 JavaScript 开源测试框架。相对其他测试框架,其一大特点就是就是内置了常用的测试工具,比如零配置、自带断言、测试覆盖率工具等功能,实现了开箱即用。

Jest 适用但不局限于使用以下技术的项目:Babel,、TypeScript、 Node、 React、Angular、Vue 等。

Jest 主要特点:

  • 零配置
  • 自带断言
  • 作为一个面向前端的测试框架, Jest 可以利用其特有的快照测试功能,通过比对 UI 代码生成的快照文件,实现对 React 等常见前端框架的自动测试。
  • 此外, Jest 的测试用例是并行执行的,而且只执行发生改变的文件所对应的测试,提升了测试速度。
  • 测试覆盖率
  • Mock 模拟

快速体验

用你喜欢的软件包管理工具来安装 Jest:

npm install --save-dev jest

给一个假定的函数写测试,这个函数的功能是两数相加。首先创建 sum.js 文件:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

接下来,创建名为 sum.test.js 的文件。这个文件包含了实际测试内容:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

将如下代码添加到 package.json 中:

{
  "scripts": {
    "test": "jest"
  }
}

jest 命令会运行项目中所有以 .test.js 结尾的文件

运行测试命令:

npm run test

image.png

配置文件

Jest 将根据项目提出一系列问题,并且将创建一个基础配置文件。文件中的每一项都配有简短的说明:

npx jest --init

详细配置信息参考:jestjs.io/docs/zh-Han…

// jest.config.js
/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/en/configuration.html
 */

module.exports = {
  // 自动 mock 所有导入的外部模块
  // automock: false,

  // 在指定次数失败后停止运行测试
  // bail: 0,

  // The directory where Jest should store its cached dependency information
  // cacheDirectory: "/private/var/folders/5h/_98rffpj1z95b_0dm76lvzm40000gn/T/jest_dx",

  // 在每个测试之间自动清除 mock 调用和实例
  clearMocks: true,

  // 是否收集测试覆盖率信息
  // collectCoverage: false,

  // 一个 glob 模式数组,指示应该为其收集覆盖率信息的一组文件
  // collectCoverageFrom: undefined,

  // 测试覆盖率报错文件输出的目录
  coverageDirectory: "coverage",

  // 忽略测试覆盖率统计
  // coveragePathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // 指示应该使用哪个提供程序检测代码的覆盖率,默认是 babel,可选 v8,但是 v8 不太稳定,建议 Node 14 以上版本使用
  // coverageProvider: "babel",

  // 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,

  // A path to a custom dependency extractor
  // dependencyExtractor: undefined,

  // Make calling deprecated APIs throw helpful error messages
  // errorOnDeprecated: false,

  // Force coverage collection from ignored files using an array of glob patterns
  // forceCoverageMatch: [],

  // A path to a module which exports an async function that is triggered once before all test suites
  // globalSetup: undefined,

  // A path to a module which exports an async function that is triggered once after all test suites
  // globalTeardown: undefined,

  // A set of global variables that need to be available in all test environments
  // globals: {},

  // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
  // maxWorkers: "50%",

  // 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: {},

  // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
  // modulePathIgnorePatterns: [],

  // Activates notifications for test results
  // notify: false,

  // An enum that specifies notification mode. Requires { notify: true }
  // notifyMode: "failure-change",

  // A preset that is used as a base for Jest's configuration
  // preset: undefined,

  // Run tests from one or more projects
  // projects: undefined,

  // Use this configuration option to add custom reporters to Jest
  // reporters: undefined,

  // Automatically reset mock state between every test
  // resetMocks: false,

  // Reset the module registry before running each individual test
  // resetModules: false,

  // A path to a custom resolver
  // resolver: undefined,

  // Automatically restore mock state between every test
  // restoreMocks: false,

  // The root directory that Jest should scan for tests and modules within
  // rootDir: undefined,

  // A list of paths to directories that Jest should use to search for files in
  // roots: [
  //   "<rootDir>"
  // ],

  // Allows you to use a custom runner instead of Jest's default test runner
  // runner: "jest-runner",

  // 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 modules that run some code to configure or set up the testing framework before each test
  // setupFilesAfterEnv: [],

  // The number of seconds after which a test is considered as slow and reported as such in the results.
  // slowTestThreshold: 5,

  // A list of paths to snapshot serializer modules Jest should use for snapshot testing
  // snapshotSerializers: [],

  // The test environment that will be used for testing
  // testEnvironment: "jest-environment-jsdom",

  // Options that will be passed to the testEnvironment
  // testEnvironmentOptions: {},

  // Adds a location field to test results
  // testLocationInResults: false,

  // The glob patterns Jest uses to detect test files
  // testMatch: [
  //   "**/__tests__/**/*.[jt]s?(x)",
  //   "**/?(*.)+(spec|test).[tj]s?(x)"
  // ],

  // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
  // testPathIgnorePatterns: [
  //   "/node_modules/"
  // ],

  // The regexp pattern or array of patterns that Jest uses to detect test files
  // testRegex: [],

  // This option allows the use of a custom results processor
  // testResultsProcessor: undefined,

  // This option allows use of a custom test runner
  // testRunner: "jasmine2",

  // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
  // testURL: "http://localhost",

  // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
  // timers: "real",

  // A map from regular expressions to paths to transformers
  // transform: undefined,

  // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
  // transformIgnorePatterns: [
  //   "/node_modules/",
  //   "\\.pnp\\.[^\\/]+$"
  // ],

  // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
  // unmockedModulePathPatterns: undefined,

  // Indicates whether each individual test should be reported during the run
  // verbose: undefined,

  // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
  // watchPathIgnorePatterns: [],

  // Whether to use watchman for file crawling
  // watchman: true,
};

Jest CLI 选项

参考:jestjs.io/zh-Hans/doc…

--watchAll

监视文件的更改并在任何更改时重新运行所有测试。

jest --watchAll

image.png

--watch

该模式需要 Git 支持。

监视 Git 仓库中的文件更改,并重新运行与已更改的文件相关的测试。

jest --watch

使用 ES6 模块

需要使用 Babel,安装所需的依赖。

npm install --save-dev babel-jest @babel/core @babel/preset-env

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

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

Jest 在运行测试的时候会自动找到 Babel 将 ES6 代码转换为 ES5 执行。

Jest 结合 Babel 的运行原理:运行测试之前,结合 Babel,先把你的代码做一次转化,模块被转换为了 CommonJS,运行转换之后的测试用例代码。

过程:

  • npm run jest
  • jest
  • babel-jest
  • babel-core
  • babel 配置文件
  • 转换为 ES5
  • 执行转换之后的测试代码

 以下是我收集到的比较好的学习教程资源,虽然不是什么很值钱的东西,如果你刚好需要,可以评论区,留言【777】直接拿走就好了

各位想获取资料的朋友请点赞 + 评论 + 收藏,三连!

三连之后我会在评论区挨个私信发给你们~

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

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

相关文章

从二叉搜索树到红黑树

二叉搜索树&#xff08;Binary Search Tree&#xff09; 特性 任意一个节点的所有左子树都比它小&#xff0c;所有右子树都比它大&#xff1b; 复杂度 当我们查找某个节点的时候&#xff0c;先从根节点开始比较&#xff0c;如果比根节点大走右子树&#xff0c;如果比根节点…

码农该如何延长周末体验感

码农该如何延长周末体验感 码农该如何延长周末体验感 码农该如何延长周末体验感1.制定合理的工作计划&#xff1a;2.实践工作与生活的平衡&#xff1a;3.学习新技术或扩展知识领域4.参与开源项目或个人项目&#xff1a;5.与同事或朋友组织活动&#xff1a;6.自己写博客或者总结…

jeecgboot新建moudle,但是访问404,需要在open moudle setting 里面设置

jeecgboot新建moudle&#xff0c;但是访问404&#xff0c;需要在open moudle setting 里面设置 首先需要确定以下3个pom.xml 最最外层的pom.xml 最最外层的pom.xml <modules><module>jeecg-boot-base-core</module><module>jeecg-module-demo</m…

string类(使用+实现)(C++)

string string类“登场”string类 - 了解string类的常用接口常见构造容量操作访问及遍历操作迭代器分类作用 增删查改操作非成员函数 string类的实现string类重要的方法实现分析介绍构造函数拷贝构造函数赋值运算符重载总结 string类整体实现代码 写时拷贝&#xff08;了解&…

金三银四好像消失了,IT行业何时复苏!

疫情时候不敢离职&#xff0c;以为熬过来疫情了&#xff0c;行情会好一些&#xff0c;可是疫情结束了&#xff0c;反而行情更差了&#xff0c; 这是要哪样 我心中不由一万个 草泥&#x1f434; 路过 我心中不惊有了很多疑惑和感叹&#xff01; 自我10连问 我的心情 自去年下…

什么是合者生情?

有人说&#xff0c;自己的命运自己掌握&#xff0c;但必须以预知自己命运如何为前提。 若不知道自己的命运如何&#xff0c;却要掌握自己的命运&#xff0c;那只是一句空话&#xff0c;是自欺欺人。 而易学在我国历史上&#xff0c;直至现在&#xff0c;都起到了重大而深远的作…

Python入门【LEGB规则、面向对象简介、面向过程和面向对象思想、面向对象是什么? 对象的进化 、类的定义、对象完整内存结构 】(十三)

&#x1f44f;作者简介&#xff1a;大家好&#xff0c;我是爱敲代码的小王&#xff0c;CSDN博客博主,Python小白 &#x1f4d5;系列专栏&#xff1a;python入门到实战、Python爬虫开发、Python办公自动化、Python数据分析、Python前后端开发 &#x1f4e7;如果文章知识点有错误…

ARM裸机-5

1、可编程器件的编程原理 1.1、电子器件的发展方向 模拟器件-->数字器件 ASIC-->可编程器件 1.2、可编程器件的特点 CPU在固定频率的时钟控制下节奏运行。 CPU可以通过总线读取外部存储设备中的二进制指令集&#xff0c;然后解码执行。 这些可以被CPU解码执行的二进制指…

SpringBoot临时属性设置

在Spring Boot中&#xff0c;可以通过设置临时属性来覆盖应用程序中定义的属性。这在某些情况下很有用&#xff0c;例如在命令行中指定配置参数或在测试环境中覆盖默认值。 你可以使用--&#xff08;双破折号&#xff09;语法来设置临时属性。以下是一些示例&#xff1a; 1. …

【点云处理教程】04 Python 中的点云过滤

一、说明 这是我的“点云处理”教程的第 4 篇文章。“点云处理”教程对初学者友好&#xff0c;我们将在其中简单地介绍从数据准备到数据分割和分类的点云处理管道。 在本教程中&#xff0c;我们将学习如何使用 Open3D 在 python 中过滤点云以进行下采样和异常值去除。使用 Open…

【GitOps系列】在 GitOps 工作流中实现蓝绿发布

文章目录 前言蓝绿发布概述手动实现蓝绿发布创建蓝色环境创建蓝色环境 Ingressroute部署绿色环境切换到绿色环境 蓝绿发布自动化安装 Argo Rollout创建 Rollout 对象创建 Service 和 Ingress访问蓝色环境发布自动化 访问 Argo Rollout Dashboard自动化原理结语 前言 在前几篇【…

Netty学习(四)

文章目录 四. 优化与源码1. 优化1.1 扩展序列化算法jdk序列化与反序列化Serializer & AlgorithmConfigapplication.properties MessageCodecSharableMessage&#xff08;抽象类&#xff09; 测试序列化测试反序列化测试 1.2 参数调优1&#xff09;CONNECT_TIMEOUT_MILLIS2&…

最强,自动化测试-自定义日志类及日志封装(实战)

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 在自定义日志之前…

【机器学习】习题3.3Python编程实现对数几率回归

参考代码 结合自己的理解&#xff0c;添加注释。 代码 导入相关的库 import numpy as np import pandas as pd import matplotlib from matplotlib import pyplot as plt from sklearn import linear_model导入数据&#xff0c;进行数据处理和特征工程 # 1.数据处理&#x…

Windows系统如何修改文件日期属性

winr键&#xff0c;输入powershell,在弹出的命令窗口输入命令&#xff0c;案例如下&#xff1a; file_address E:\_OrderingProject\\PIC1101\ldv1s_0830_ec_result.tiftime_change "07/12/2022 20:42:23" 修改文件创建时间&#xff1a;creationtime $(Get-Item fi…

COMSOL三维Voronoi图泰森多边形3D模型轴压模拟及建模教程

多晶体模型采用三维Voronoi算法生成&#xff0c;试件尺寸为150150300mm棱柱模型&#xff0c;对晶格指定五种不同材料&#xff0c;实现晶格间的差异性。 对试件进行力学模拟&#xff0c;下侧为固定边界&#xff0c;限制z方向的位移&#xff0c;上表面通过给定位移的方式实现轴…

P2P网络NAT穿透原理(打洞方案)

1.关于NAT NAT技术&#xff08;Network Address Translation&#xff0c;网络地址转换&#xff09;是一种把内部网络&#xff08;简称为内网&#xff09;私有IP地址转换为外部网络&#xff08;简称为外网&#xff09;公共IP地址的技术&#xff0c;它使得一定范围内的多台主机只…

某拍房数据采集

某拍房数据采集 某拍房数据采集声明1.逆向目标2.寻找加密位置3.分析加密参数4.python代码书写 某拍房数据采集 声明 本文章中所有内容仅供学习交流&#xff0c;抓包内容、敏感网址、数据接口均已做脱敏处理&#xff0c;严禁用于商业用途和非法用途&#xff0c;否则由此产生的…

yo!这里是Linux常见命令总结

目录 前言 常见命令 ls指令 pwd指令 cd指令 touch指令 tree指令 mkdir指令&&rmdir指令 rm指令 man指令 cp指令 mv指令 echo指令 cat指令&&tac指令 more指令 less指令 head指令&&tail指令 find指令 grep指令 alias指令&&u…

NAT原理(网络地址转换)

NAT原理 网络地址转换&#xff08;Network Address Translation&#xff0c;简称NAT&#xff09; 是一种网络通信协议&#xff0c;它是在网络层上对IP地址进行转换的技术。 NAT技术可以将内部网络中的私有IP地址转换为公共IP地址&#xff0c;以便内部网络中的设备能够访问互…