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

2admgd59  于 2023-01-17  发布在  其他
关注(0)|答案(3)|浏览(98)

我已经用next.js建立了我的投资组合网页,现在我需要测试它。为了测试express服务器,我使用了supertest。但问题是我需要重构express来使用它。因为supertest在监听之前需要访问app()。
我开始使用在node.js app中实现的方法,将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;

然后在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);
  });

有了这个设置,express正在侦听,我可以连接到mongodb,在启动过程中没有问题。
当我请求localhost:3000时,localhost没有响应,它一直旋转直到超时

dgtucam1

dgtucam11#

创建测试客户端:

// 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));
};

使用以下工具测试您的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" });
  });
});
yqhsw0fo

yqhsw0fo2#

对于那些希望添加查询参数的用户,答案如下:

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

export const handlerRequester = (handler: NextApiHandler) => {
  const listener: RequestListener = (req, res) => {
    let query = {}
    let queryUrl = req.url.split('?')[1]
    if (queryUrl) {
      queryUrl
        .split('&')
        .map((p) => [p.split('=')[0], p.split('=')[1]])
        .forEach((k) => {
          query[k[0]] = k[1]
        })
    }
    return apiResolver(
      req,
      res,
      query,
      handler,
      {
        previewModeEncryptionKey: '',
        previewModeId: '',
        previewModeSigningKey: '',
      },
      false
    )
  }
  const server = createServer(listener)
  return [request(server), server]
}
blmhpbnm

blmhpbnm3#

我刚刚发布了一个新的npm软件包,在这里处理这种情况:https://www.npmjs.com/package/nextjs-http-supertest
欢迎测试并给予我反馈!

相关问题