【问题标题】:Supertest and jest: cannot close express connection超测和开玩笑:无法关闭快速连接
【发布时间】:2021-06-04 19:01:54
【问题描述】:

我正在使用 jest 和 supertest 来引发 express 实例并在其上运行测试。

我遇到了仍然无法解决的繁忙端口问题。

在我的测试中,我做了下一个:

import supertest from 'supertest';
const agent = supertest(app);

然后我向代理提出请求,一切正常。 直到我运行另一个测试。 在 app.js 我有:

var app = express();

app.post('/auth/changePassword',VerifyToken, auth.changePassword);

app.listen(4001, function () {
    console.log('Server is running');
});

所以第一个规范运行完美。但第二次尝试监听已经在使用的端口。 我真的不知道怎么关闭这里的连接。

我尝试了app.close(),但这种方法出错了。这很清楚,我必须分配

server = app.listen(4001, function () {
    console.log('Server is running');
});
server.close();

但不知道我该怎么做。 我还尝试在 jest.setup 中预设代理并将其分配给全局变量

import app from "../../server/app";
import supertest from 'supertest';

const agent = supertest(app);
global.agent = agent;

但情况是一样的,第一次测试通过,第二次尝试在同一个端口上提出 express。

【问题讨论】:

    标签: express jestjs supertest


    【解决方案1】:

    Supertest 能够为您启动和停止您的应用程序 - 您永远不需要在测试期间显式终止 express 服务器(即使并行运行时也是如此)

    问题在于,在app.js 中,您的服务器实际上已启动 - 这意味着当运行应用程序测试时,您的服务器会在每次读取 app.js 时启动(或每个测试用例一次)

    您可以通过将server start 逻辑拆分为单独的文件来解决此问题,这样导入app.js 不会启动应用程序(而是返回一个快速服务器实例)我通常使用的模式是:

    // app.js
    import express from 'express'
    export const app = express();
    
    app.get("/example", (req,res) => {
      return res.status(200).json({data: "running"})
    })
    
    // server.js
    import app from "./app"
    
    app.listen(3000, () => console.log("listening on 3000"));
    
    // app.spec.js
    import app from "./app"
    import request from "supertest"
    
    it("should be running", async () => {
      const result = await request(app).get("/example");
    
      expect(result.body).toEqual({data: "running"});
    });
    

    【讨论】:

      猜你喜欢
      • 2022-08-07
      • 2021-11-13
      • 1970-01-01
      • 2022-09-27
      • 2018-07-02
      • 2017-10-01
      • 1970-01-01
      • 2022-07-26
      • 2018-06-04
      相关资源
      最近更新 更多