【问题标题】:Multiple server instance attempts while running jest运行 jest 时多次尝试服务器实例
【发布时间】:2019-03-31 21:11:30
【问题描述】:

好的,所以我一直在使用 jest 和 supertest 为我的 node.js 应用程序编写测试,对于第一个之后的每个测试套件,我都会收到错误 Error: listen EADDRINUSE: address already in use :::3000,我相信这是因为它试图启动每个测试文件上的服务器(我在/tests 中有多个测试文件*.test.js

在每个测试文件中描述测试之前的顶部看起来像这样

const request = require("supertest");
const app = require("../index.js"); // the express server

jest.setTimeout(30000);

let token;

beforeAll(done => {
  request(app)
    .post("/api/users/login")
    .send({
      email: "email here",
      password: "password here"
    })
    .end((err, response) => {
      token = response.body.data; // save the token!
      done();
    });
});

afterAll(done => {
  //logout() //Not implemented yet
  done();
});

/* Test starts here */

那么,我需要知道如何防止 jest 尝试初始化我的服务器的多个实例?是否可以说所有这些代码都在预测试文件中运行?有什么我可以添加到我的afterAll 以使其停止服务器,所以当另一个测试开始时我很好吗?非常感谢。

【问题讨论】:

    标签: node.js mongodb jestjs supertest


    【解决方案1】:

    问题来了

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

    每次您尝试要求 index.js 时,您从技术上将 index.js 中的所有代码复制粘贴到您的测试脚本中。

    由于您同时运行多个测试文件,每个测试都会尝试在index.js内运行相同的代码

    你可以阅读更多关于这个http://fredkschott.com/post/2014/06/require-and-the-module-system/

    【讨论】:

    • 谢谢,我知道这是错误,所以我想到了 2 种可能的解决方案,要么在 afterAll 中的每次测试后终止从 index.js 运行的任何内容,要么有一个单独的文件运行预测试以使服务器只运行一次,知道我该怎么做吗?
    • 我认为您需要将核心服务器与测试分开,您可以使用concurrently 同时提供的第一个参数是npm run start 来运行您的服务器,第二个参数是npm run test例如运行你所有的测试......它看起来像这样"concurrently \"npm run start\" \"npm run test1\" \"npm run test2\" "
    【解决方案2】:

    好的,所以虽然在每次启动时删除连接并根据@Omar Sherif 的回答同时使用是一种有效的解决方法,但我发现它不必要地复杂,根据 jest 的文档设置 globalSetup 也是相当不必要的麻烦。

    我找到的一个简单解决方案如下;由于运行 jest 将 NODE_ENV 设置为测试,在我的 index.js 文件夹中,而不是只让我的服务器侦听不必要的网络端口,我添加了一个非常简单的 if 条件。

    if (process.env.NODE_ENV !== "test") {
      app.listen(port, () => console.log(`Server Running on ${port}`));
    }
    

    这似乎起到了作用。谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多