使用 Jest 开始对你的 JavaScript 进行单元测试
大多数 JavaScript 开发人员要么忽略单元测试,要么对它漠不关心。然而,单元测试对于在问题导致用户流失之前将其找出并解决至关重要。
虽然我们始终可以进行手动测试,但使用测试框架进行测试效率要高得多。在今天的文章中,我们将使用这样一个框架开始进行单元测试。
什么是玩笑?
Jest 是一个流行的 JavaScript 单元测试框架,它能最大限度地缩短测试准备时间。它使用匹配器(matcher)来测试 JavaScript 代码库。匹配器接收一个预期值,并将其与 expect 函数的输出进行比较,expect 函数则以 JavaScript 代码作为输入。
Jest 随后会提供详细的测试结果,以便于调试,在大多数情况下,它会指出错误发生的确切位置。
匹配器
Jest包含的一些匹配器有:
- toBe - 用于按值匹配原始数据类型。
- toBeLessThanOrEqual - 检查输出值是否小于某个特定值。
- toBeCloseTo 函数主要用于比较浮点数值。由于它不比较精确值,因此有助于避免因舍入误差导致的误报。
- toMatch - 用于与正则表达式进行匹配。
- toEqual - 与 toBe 匹配器类似,但它是为引用数据类型(例如对象)而设计的。
- toContain - 顾名思义,它检查特定元素是否存在于给定的引用类型(例如数组)中。
项目筹备
为了搭建我们的项目,我们将创建一个新的 Node 项目:npm init
然后我们可以使用以下命令安装 Jest:npm install —save-dev
接下来,package.json我们将在代码中添加以下脚本:
最后,我们将创建两个文件:functions.js和functions.test.js
一般来说,对于每个需要测试的 JavaScript 代码,只需创建一个名为 .test.js 的额外文件即可。
在我们的 JavaScript 文件中使用 Jest
然后我们可以像这样实现 Jest:
| //function to add | |
| const add = (num1, num2) => num1 + num2; | |
| //function to multiply | |
| const multiply = (num1, num2) => num1 * num2; | |
| //function to create an Object | |
| const createUser = () => { | |
| const user = { | |
| firstName: "Luke", | |
| lastName: "Skywalker", | |
| }; | |
| return user; | |
| }; | |
| //exporting | |
| module.exports = { add, multiply, createUser }; |
| //importing my file to be tested | |
| const func = require("./functions"); | |
| //testing the add function using toBe matcher | |
| test("adds 2 and 2 to give 4", () => { | |
| expect(func.add(2, 2)).toBe(4); | |
| }); | |
| //testing the multiply function using toBe matcher | |
| test("multiplies 12 and 13 to give 156", () => { | |
| expect(func.multiply(12, 13)).toBe(156); | |
| }); | |
| //using the toBeLessThanOrEqual matcher | |
| test("Should be under 25", () => { | |
| const weight = 70; | |
| const height = 180 / 100; | |
| const bmi = weight / (height * height); | |
| expect(bmi).toBeLessThanOrEqual(25); | |
| }); | |
| //using the toBeCloseTo matcher for floats | |
| test("Floating point numbers", () => { | |
| const value = 1.3 + 2.9; | |
| expect(value).toBeCloseTo(4.2); | |
| }); | |
| //using the toMatch matcher for regex | |
| test("Secret Ingredient", () => { | |
| expect("There is no secret ingredient").toMatch(/secret/); | |
| }); | |
| //using the toEqual matcher for Object type | |
| test("Luke Skywalker", () => { | |
| expect(func.createUser()).toEqual({ | |
| firstName: "Luke", | |
| lastName: "Skywalker", | |
| }); | |
| }); | |
| //using the toContain matcher for specific element in array | |
| test("Master Oogway", () => { | |
| const hisWords = ["There", "are", "no", "accidents"]; | |
| expect(hisWords).toContain("accidents"); | |
| }); |
运行 Jest
现在我们可以使用以下命令运行 Jest:npm run test
请查看以下输出:
好了!我们刚刚使用 Jest 搭建了第一个测试套件。
完成测试、修复所有问题并准备好代码部署后,您可以使用Codesphere便捷的云部署服务。只需几分钟即可完成项目设置并使其上线,让您可以专注于手头最重要的任务:编写代码。
请在下方留言告诉我们您正在建造什么!
文章来源:https://dev.to/codesphere/start-unit-testing-your-javascript-with-jest-4lid

