Skip to content

单元测试 Suite for Math Utility

入门 约 30 分钟

你将构建什么

math utility 模块使用函数 for addition, subtraction, multiplication, division, and factorial, 沿着使用 comprehensive Jest 测试 suite covering normal 情况, 边缘情况, and 错误 handling.

学习目标

  • 编写 math utility 模块使用 5 函数
  • 创建 Jest 测试 suite 使用 at 最少 15 测试情况
  • Cover normal 输入, 边缘情况 (零, 负), and 错误情况 (division 通过零)
  • Use 排列-Act-Assert 模式 consistently
  • Achieve 100% 语句 coverage

前置要求

  • 基础 JavaScript (函数, arithmetic, 错误 handling)
  • 节点.js and npm 安装
  • 理解的 什么单元测试是

步骤

  1. 1

    设置项目

    创建新 directory, 运行 npm init -y, and 安装 Jest: npm 安装 --保存-dev jest. 添加测试 script 到包.JSON: "测试": "jest".

    代码
    {
      "scripts": {
        "test": "jest"
      }
    }

    预期结果

    包.JSON 有测试 script and jest 是 in devDependencies.

  2. 2

    创建 math utility 模块

    创建 math.js 使用函数: 添加, subtract, multiply, 划分 (throws on division 通过零), and factorial (throws on 负输入).

    代码
    function add(a, b) { return a + b; }
    function subtract(a, b) { return a - b; }
    function multiply(a, b) { return a * b; }
    function divide(a, b) {
      if (b === 0) throw new Error('Division by zero');
      return a / b;
    }
    function factorial(n) {
      if (n < 0) throw new Error('Negative input');
      if (n <= 1) return 1;
      return n * factorial(n - 1);
    }
    module.exports = { add, subtract, multiply, divide, factorial };

    预期结果

    math.js 导出所有 five 函数.

  3. 3

    编写测试 for 添加 and subtract

    创建 math.测试.js. 编写测试 for 添加 (正, 负, 零) and subtract using AAA 模式.

    代码
    const { add, subtract } = require('./math');
    describe('add', () => {
      test('adds two positive numbers', () => {
        expect(add(2, 3)).toBe(5);
      });
      test('handles negative numbers', () => {
        expect(add(-1, -1)).toBe(-2);
      });
      test('handles zero', () => {
        expect(add(0, 5)).toBe(5);
      });
    });

    预期结果

    运行 npm 测试 — 所有添加 and subtract 测试通过.

  4. 4

    编写测试 for 划分 and factorial

    添加测试 for 划分 (包含错误情况) and factorial (包含负 错误情况). Use toThrow for 错误情况.

    代码
    describe('divide', () => {
      test('divides correctly', () => {
        expect(divide(10, 2)).toBe(5);
      });
      test('throws on division by zero', () => {
        expect(() => divide(1, 0)).toThrow('Division by zero');
      });
    });

    预期结果

    所有测试通过, 包含错误情况.

  5. 5

    检查 coverage

    运行 npx jest --coverage and 验证 100% 语句 coverage.

    预期结果

    Coverage report shows 100% 语句, 分支, 函数, and 行.

自己动手试试

你学到了什么

你学习如何 结构单元测试 suite using Jest, apply 排列-Act-Assert 模式, 测试错误情况使用 toThrow, and measure code coverage. 这些 skills 表单基础的 测试-driven development.

相关资源

相关课程

相关练习

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题