Node.js:Jest测试框架测试test代码

简介: Node.js:Jest测试框架测试test代码

Jest 是一个令人愉快的 JavaScript 测试框架,专注于 简洁明快。

目录

VS Code插件

Jest

// 如果不想自动运行,可以设置关闭
"jest.autoRun": "off"

安装jest

$ pnpm i -D jest

基本使用-Node.js

目录结构

$ tree -I node_modules
.
├── package.json
├── pnpm-lock.yaml
├── sum.js
└── sum.test.js

依赖 package.json

{
    "devDependencies": {
        "jest": "^29.3.1"
    }
}

功能函数 sum.js

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

测试函数 sum.test.js

const sum = require("./sum.js");
test("1 + 2 = 3", function () {
  expect(sum(1, 2)).toBe(3);
});

运行测试

$ npx jest
 PASS  ./sum.test.js
  ✓ 1 + 2 = 3 (1 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.57 s
Ran all test suites.

匹配器

// 精确匹配
expect(1).toBe(1);
// 递归检查对象或数组的每个字段
expect([1, 2, 3]).toEqual([1, 2, 3]);

测试函数调用情况

map.js

function map(list, callback) {
  return list.map(callback);
}
module.exports = map;

map.test.js

const map = require("./map.js");
// 定义分组
describe("测试map函数", () => {
  test("测试回调函数调用次数", function () {
    const fn = jest.fn((x) => x * 2);
    map([1, 2, 3], fn);
    // 测试回调函数调用次数
    expect(fn.mock.calls.length).toEqual(3);
  });
  test("测试回调函数返回值", function () {
    const fn = jest.fn((x) => x * 2);
    map([1, 2, 3], fn);
    expect(fn.mock.results[0].value).toEqual(2);
    expect(fn.mock.results[1].value).toEqual(4);
    expect(fn.mock.results[2].value).toEqual(6);
  });
});

查看测试覆盖率

$ npx jest --coverage
 PASS  ./map.test.js
  测试map函数
    ✓ 测试回调函数调用次数 (2 ms)
    ✓ 测试回调函数返回值 (1 ms)
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 map.js   |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.757 s, estimated 1 s
Ran all test suites.

目录coverage/lcov-report 下会生成一个网页版的覆盖率报告

image.png

基本使用-ES6

安装依赖

npm install -D jest babel-jest babel-core babel-preset-env regenerator-runtime

高版本

npm install -D jest babel-jest @babel/core @babel/preset-env

备注:安装babel 为了让jest 支持ES6语法 import/export

package.json

{
  "type": "module",
  "scripts": {
    "test": "jest --verbose"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-jest": "^28.1.3",
    "babel-preset-env": "^1.7.0",
    "jest": "^28.1.3",
    "regenerator-runtime": "^0.13.9"
  }
}

babel 配置文件 .babelrc

babel-preset-env

{
  "presets": ["env"]
}

@babel/preset-env

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

测试示例

src/functions.js

export default {
  sum(a, b) {
    return a + b
  },
}

tests/functions.test.js

import functions from '../src/functions'
test('sum(2 + 2) 等于 4', () => {
  expect(functions.sum(2, 2)).toBe(4)
})

运行测试

$ npx jest
 PASS  tests/functions.test.js
  ✓ sum(2 + 2) 等于 4 (1 ms)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.141 s
Ran all test suites.

参考

使用Jest测试JavaScript (入门篇)

js:jest报错RangeError: Maximum call stack size exceeded

【Bilibili视频】JS 测试:Jest 框架入门教程


相关文章
|
3月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
372 1
|
4月前
|
Web App开发 人工智能 JavaScript
主流自动化测试框架的技术解析与实战指南
本内容深入解析主流测试框架Playwright、Selenium与Cypress的核心架构与适用场景,对比其在SPA测试、CI/CD、跨浏览器兼容性等方面的表现。同时探讨Playwright在AI增强测试、录制回放、企业部署等领域的实战优势,以及Selenium在老旧系统和IE兼容性中的坚守场景。结合六大典型场景,提供技术选型决策指南,并展望AI赋能下的未来测试体系。
|
4月前
|
算法 IDE Java
Java 项目实战之实际代码实现与测试调试全过程详解
本文详细讲解了Java项目的实战开发流程,涵盖项目创建、代码实现(如计算器与汉诺塔问题)、单元测试(使用JUnit)及调试技巧(如断点调试与异常排查),帮助开发者掌握从编码到测试调试的完整技能,提升Java开发实战能力。
476 0
|
2月前
|
SQL 安全 Linux
Metasploit Pro 4.22.8-20251014 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-20251014 (Linux, Windows) - 专业渗透测试框架
163 1
Metasploit Pro 4.22.8-20251014 (Linux, Windows) - 专业渗透测试框架
|
2月前
|
Linux 网络安全 iOS开发
Metasploit Framework 6.4.95 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.95 (macOS, Linux, Windows) - 开源渗透测试框架
210 1
Metasploit Framework 6.4.95 (macOS, Linux, Windows) - 开源渗透测试框架
|
2月前
|
安全 Java 测试技术
《深入理解Spring》单元测试——高质量代码的守护神
Spring测试框架提供全面的单元与集成测试支持,通过`@SpringBootTest`、`@WebMvcTest`等注解实现分层测试,结合Mockito、Testcontainers和Jacoco,保障代码质量,提升开发效率与系统稳定性。
|
3月前
|
安全 Linux 网络安全
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
313 2
Metasploit Pro 4.22.8-2025091701 (Linux, Windows) - 专业渗透测试框架
|
3月前
|
Linux 网络安全 iOS开发
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
420 1
Metasploit Framework 6.4.90 (macOS, Linux, Windows) - 开源渗透测试框架
|
3月前
|
安全 Linux 网络安全
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
Metasploit Framework 6.4.88 (macOS, Linux, Windows) - 开源渗透测试框架
581 0