如何在 next.js 中使用 supertest 测试 Express 服务器?

Yil*_*maz 5 javascript node.js express supertest next.js

我已经使用 next.js 构建了我的投资组合网页,现在我需要测试它。为了测试 Express 服务器,我使用 supertest。但问题是我需要重构express才能使用它。因为supertest在监听之前需要访问app()。

我开始采用以前在 Node.js 应用程序中实现的方式。将express代码放入app.js中,并在index.js中调用。

const express = require("express");
const server = express();
const authService = require("./services/auth");
const bodyParser = require("body-parser");
//put all the middlewares here

module.exports = server;
Run Code Online (Sandbox Code Playgroud)

然后在index.js中

const server = require("express")();
// const { parse } = require("url");
const next = require("next");
const routes = require("../routes");

const path = require("path");
require("./mongodb");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
// const handle = app.getRequestHandler(); //this is built in next route handler
const handle = routes.getRequestHandler(app);


app
  .prepare()
  .then(() => {
     const server = require("./app");
     //I required this outside too but it did not solve the issue


    server.listen(3000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:3000");
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });
Run Code Online (Sandbox Code Playgroud)

通过此设置,express 正在监听,我能够连接到 mongodb,在启动过程中没有问题。

当我请求 localhost:3000 时,本地主机没有响应,它一直旋转直到超时

Mik*_*ank 3

创建测试客户端:

// test-client.ts

import { createServer, RequestListener } from "http";
import { NextApiHandler } from "next";
import { apiResolver } from "next/dist/next-server/server/api-utils";
import request from "supertest";

export const testClient = (handler: NextApiHandler) => {
  const listener: RequestListener = (req, res) => {
    return apiResolver(
      req,
      res,
      undefined,
      handler,
      {
        previewModeEncryptionKey: "",
        previewModeId: "",
        previewModeSigningKey: "",
      },
      false
    );
  };

  return request(createServer(listener));
};
Run Code Online (Sandbox Code Playgroud)

使用以下方法测试您的 API:

// user.test.ts

import viewerApiHandler from "../api/user";
import { testClient } from "../utils/test-client";

const request = testClient(viewerApiHandler);

describe("/user", () => {
  it("should return current user", async () => {
    const res = await request.get("/user");
    expect(res.status).toBe(200);
    expect(res.body).toStrictEqual({ name: "Jane Doe" });
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 如何调用“request”函数并传递查询参数(硬编码为“undefined”)? (2认同)