Jest - 入门
在本章中,我们将向您介绍 Jest 的基础知识,以帮助您开始测试,无论您使用的是小型函数还是大型应用程序。在本章结束时,您将能够:
- 使用 Jest 编写您的第一个测试。
- 使用基本断言来验证您的代码。
- 有效地组织和构建您的测试。
Jest - 第一个测试
在本节中,我们将逐步指导您编写和运行您的第一个 Jest 测试。
设置您的项目
在编写测试之前,请确保您的项目中安装了 Jest。如果您尚未安装 Jest,请查看上一章中的安装步骤。
创建一个简单的函数进行测试
首先,让我们创建一个将两个数字相加的简单函数。我们将使用 Jest 测试此函数。创建一个名为 sum.js 的文件并编写以下代码:
// sum.js function sum(a, b) { return a + b; } module.exports = sum;
为函数编写测试
接下来,我们将为 sum 函数编写测试。
- 在您的项目中,如果不存在 __tests__ 文件夹,请创建一个。
- 在 __tests__ 文件夹中,创建一个名为 sum.test.js 的文件。
- 在 sum.test.js 中,编写以下测试代码:
// sum.test.js const sum = require('../sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
测试说明:
- test(): 是用于定义测试用例的 Jest 函数。
- expect(): 用于检查函数的结果。
- .toBe(): 是一个 Jest 匹配器,用于检查结果是否等于预期值。
运行测试
现在您已经编写了测试,让我们运行它。打开终端并输入:
npm test
Jest 将运行您的测试并在终端中显示结果:
了解输出
运行测试后,如果测试通过,您将看到类似以下内容:
> jest PASS __tests__/sum.test.js √ adds 1 + 2 to equal 3 (3 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.557 s, estimated 3 s
处理测试失败
如果您的代码中有错误,Jest 将显示失败消息。例如,如果 sum 函数有误,请按如下方式修改它:
// sum.js (incorrect version) function sum(a, b) { return a - b; // Wrong operation } module.exports = sum;
然后再次运行 npm test。您将在终端中看到以下内容:
> jest FAIL __tests__/sum.test.js ✕ adds 1 + 2 to equal 3 (4 ms) Test Suites: 1 failed, 1 total Tests: 0 passed, 1 failed, 1 total
修复错误
要修复测试,请更正 sum 函数:
// sum.js (correct version) function sum(a, b) { return a + b; // Correct operation } module.exports = sum;
再次运行 npm test,这次测试应该会通过。
Jest - 基本断言
在 Jest 中,断言用于检查测试中的值是否符合预期条件。下面,我们将介绍 Jest 中最常用的断言,并提供如何使用它们的示例。
使用 toBe() 实现精确相等
toBe() 匹配器检查一个值是否完全等于另一个值,这对于数字或字符串等原始类型非常有效。
test('subtract five minus three equals two', () => { expect(5 - 3).toBe(2); // Passes because 5 - 3 equals 2 });
此处,toBe(2) 检查 5 - 3 的结果是否等于 2。如果值正确,则测试通过。
使用 toEqual() 进行深度相等
toEqual() 匹配器检查两个对象或数组是否深度相等。它对于比较可能具有嵌套值的对象或数组很有用。
test('object assignment with new values', () => { const data = { fruit: 'apple' }; data['color'] = 'red'; expect(data).toEqual({ fruit: 'apple', color: 'red' }); });
在此测试中,toEqual() 检查数据对象是否等于 { fruit: 'apple', color: 'red' }。当对象具有相同的值时,测试通过。
使用 toBeTruthy() 和 toBeFalsy()
- toBeTruthy() 检查值是否为真(即,在 JavaScript 中计算结果为 true 的值)。
- toBeFalsy() 检查值是否为假(即,在 JavaScript 中计算结果为 false 的值)。
test('truthy test with a non-zero number', () => { expect(10).toBeTruthy(); // Passes because 10 is truthy }); test('带有空字符串的 falsy 测试', () => { expect('').toBeFalsy(); // 通过,因为空字符串是假的 });
在这些测试中,10 为真,而空字符串 '' 为假,因此两个测试都通过。
使用 toBeNull()
toBeNull() 匹配器用于检查值是否恰好为 null。当您想要确认变量明确设置为 null 时,这很有用。
test('检查值是否为 null', () => { const value = null; expect(value).toBeNull(); // 通过,因为值为 null });
测试将通过,因为值为 null。
使用 toBeDefined()
toBeDefined() 匹配器用于检查值是否未定义。当您想要确认变量是否已分配值(即已定义)时,它很有用。
test('checks if value is defined', () => { const value = 'Hello'; expect(value).toBeDefined(); // Passes because the value is defined });
此测试通过,因为值已分配 'Hello'。
使用 toBeUndefined()
toBeUndefined() 匹配器检查值是否未定义。当您想确认变量尚未赋值时,这很有用。
test('检查值是否未定义', () => { let value; expect(value).toBeUndefined(); // 由于值未定义,因此通过 });
测试通过,因为值未分配且隐式未定义。
Jest - 测试结构
在本节中,我们将解释如何构建 Jest 测试并以一种使代码更易于维护和理解的方式组织它们。
测试结构概述
Jest 测试遵循简单的结构,其中包括三个主要部分:
- Describe 块:将相关测试分组在一起。
- 测试用例:定义单个测试场景。
- 断言:检查输出是否与预期结果匹配。
使用 Describe 块对测试进行分组
describe() 块用于将相关测试分组在一个共同的标签。这样可以更轻松地按特性或功能组织测试。
// 目的:将相关测试组合在一起 describe('Calculator Functionality', () => { // 此处为加法和减法的相关测试 });
您还可以嵌套 describe() 块以获得更复杂的测试结构。
使用 test() 编写测试用例
test() 函数用于定义每个单独的测试。在此函数中,您可以描述要测试的内容以及预期结果应该是什么。
describe('Simple Math', () => { test('adds 2 and 3 correctly', () => { expect(2 + 3).toBe(5); // Adds 2 and 3, expects 5 }); test('subtracts 5 from 10 correctly', () => { expect(10 - 5).toBe(5); // Subtracts 5 from 10, expects 5 }); });
您可以将多个测试用例分组到 describe() 块中,以便更好地组织。
使用断言验证输出
断言用于检查测试结果是否与预期值匹配。Jest 提供了几个匹配器来执行不同的检查。
- toBeGreaterThan():检查数字是否大于指定值。
- toBeLessThan():检查数字是否小于指定值。
describe('Basic Assertions', () => { test('checks if 10 is greater than 5', () => { expect(10).toBeGreaterThan(5); // Passes because 10 > 5 }); test('checks if 2 is less than 5', () => { expect(2).toBeLessThan(5); // Passes because 2 < 5 }); });
完整示例
让我们实现一个带有加法和减法的简单计算器并为其编写测试。
创建计算器函数
创建文件 calculator.js 并编写以下代码:
// 计算器函数 function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract };
为计算器编写测试
接下来,在 calculator.test.js 中为 add() 和 subtract() 函数创建测试套件。
const { add, subtract } = require('./calculator'); describe('Calculator Functionality', () => { // 测试加法 describe('Addition', () => { test('adds 2 and 3 correctly', () => { expect(add(2, 3)).toBe(5); }); test('adds negative numbers correctly', () => { expect(add(-2, -3)).toBe(-5); }); test('adds a positive and a negative number correctly', () => { expect(add(10, -5)).toBe(5); }); }); // 测试减法 describe('Subtraction', () => { test('subtracts 5 from 10 correctly', () => { expect(subtract(10, 5)).toBe(5); }); test('handles negative results', () => { expect(subtract(5, 10)).toBe(-5); }); test('subtracts a negative number correctly', () => { expect(subtract(10, -5)).toBe(15); }); }); });
add() 函数将两个数字相加,而 subtract() 函数将一个数字与另一个数字相减。测试检查这两个函数是否能正确处理正数和负数。