ホームページ >ウェブフロントエンド >jsチュートリアル >Jest と Supertest を使用した REST API のテスト ✅

Jest と Supertest を使用した REST API のテスト ✅

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-12-28 20:36:11541ブラウズ

初出発行元: 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 リクエストを受け入れる Express サーバー。どちらかが欠けている場合、ステータス 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 アプリは、スーパーテストで使用するためにエクスポートされます。他の 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 ✅

jest や jest Runner などの VS Code 拡張機能を使用している場合は、それが自動的に機能します。

Testing REST APIs using Jest and Supertest ✅

これが API エンドポイントを簡単にテストする方法です。 ?

Testing REST APIs using Jest and Supertest ✅

以上がJest と Supertest を使用した REST API のテスト ✅の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。