搜索
首页web前端js教程使用 Jest 和 Supertest 测试 REST API ✅

最初发布:souvikinator.xyz

以下是如何为 API 端点设置单元测试。

我们将使用以下 NPM 包:

  • 服务器的Express(可以使用任何其他框架)
  • 开玩笑
  • 超级测试

VS Code 扩展使用:

  • 开玩笑
  • 玩笑跑者

安装依赖项

npm install express
npm install -D jest supertest

目录结构如下:

Testing REST APIs using Jest and Supertest ✅

并且不要忘记 package.json

{
  "name": "api-unit-testing",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest api.test.js",
    "start":"node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  },
  "devDependencies": {
    "jest": "^28.1.2",
    "supertest": "^6.2.3"
  }
}

创建一个简单的 Express 服务器

一个快速服务器,在 /post 端点上接受带有正文和标题的 POST 请求。如果其中之一缺失,则会返回状态 400 Bad Request。

// app.js
const express = require("express");
const app = express();

app.use(express.json());

app.post("/post", (req, res) => {
  const { title, body } = req.body;

  if (!title || !body)
    return res.sendStatus(400).json({ error: "title and body is required" });

  return res.sendStatus(200);
});

module.exports = app;
const app = require("./app");
const port = 3000;

app.listen(port, () => {
  console.log(`http://localhost:${port} ?`);
});

express 应用程序已导出以与 supertest 一起使用。使用其他 HTTP 服务器框架也可以完成相同的操作。

创建测试文件

// api.test.js
const supertest = require("supertest");
const app = require("./app"); // express app

describe("Creating post", () => {
    // test cases goes here
});

Supertest 负责运行服务器并为我们发出请求,而我们则专注于测试。

express 应用程序被传递给超级测试代理,并将express 绑定到随机可用端口。然后我们可以向所需的 API 端点发出 HTTP 请求,并将其响应状态与我们的期望进行比较:

 const response = await supertest.agent(app).post("/post").send({
        title: "Awesome post",
    body: "Awesome post body",
 });

我们将为 3 个案例创建测试:

  1. 当标题和正文都提供时
  test("creating new post when both title and body are provided", async () => {
    const response = await supertest.agent(app).post("/post").send({
      title: "Awesome post",
      body: "Awesome post body",
    });

        // comparing response status code with expected status code
    expect(response.statusCode).toBe(200);
  });
  1. 当其中任何一个失踪时
  test("creating new post when either of the data is not provided", async () => {
    const response = await supertest.agent(app).post("/post").send({
      title: "Awesome post",
    });

    expect(response.statusCode).toBe(400);
  });
  1. 当他们俩都失踪时
  test("creating new post when no data is not provided", async () => {
    const response = await supertest.agent(app).post("/post").send();

    expect(response.statusCode).toBe(400);
  });

最终代码应如下所示:

const supertest = require("supertest");
const app = require("./app"); // express app

describe("Creating post", () => {

  test("creating new post when both title and body are provided", async () => {
    const response = await supertest.agent(app).post("/post").send({
      title: "Awesome post",
      body: "Awesome post body",
    });
    expect(response.statusCode).toBe(200);
  });

  test("creating new post when either of the data is not provided", async () => {
    const response = await supertest.agent(app).post("/post").send({
      title: "Awesome post",
    });
    expect(response.statusCode).toBe(400);
  });

  test("creating new post when no data is not provided", async () => {
    const response = await supertest.agent(app).post("/post").send();
    expect(response.statusCode).toBe(400);
  });
});

运行测试

使用以下命令运行测试:

npm run test

Testing REST APIs using Jest and Supertest ✅

如果使用 VS Code 扩展(例如 jest 和 jest runner),那么它会为您完成工作。

Testing REST APIs using Jest and Supertest ✅

这就是我们如何轻松测试 API 端点的方法。 ?

Testing REST APIs using Jest and Supertest ✅

以上是使用 Jest 和 Supertest 测试 REST API ✅的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

node.js流带打字稿node.js流带打字稿Apr 30, 2025 am 08:22 AM

Node.js擅长于高效I/O,这在很大程度上要归功于流。 流媒体汇总处理数据,避免内存过载 - 大型文件,网络任务和实时应用程序的理想。将流与打字稿的类型安全结合起来创建POWE

Python vs. JavaScript:性能和效率注意事项Python vs. JavaScript:性能和效率注意事项Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

JavaScript的起源:探索其实施语言JavaScript的起源:探索其实施语言Apr 29, 2025 am 12:51 AM

JavaScript起源于1995年,由布兰登·艾克创造,实现语言为C语言。1.C语言为JavaScript提供了高性能和系统级编程能力。2.JavaScript的内存管理和性能优化依赖于C语言。3.C语言的跨平台特性帮助JavaScript在不同操作系统上高效运行。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。