gpt4 book ai didi

node.js - NodeJS:发现错误:听 EADDRINUSE:::3000?

转载 作者:搜寻专家 更新时间:2023-10-31 23:30:22 29 4
gpt4 key购买 nike


我目前正面临一个我无法解决的错误,我已经苦苦挣扎了几个小时。
我正在使用以下版本:
Node :8.11.3
express :4.16.3
Jest :22.2.2
Mongoose :5.2.3

我正在尝试使用 jest 进行一些集成测试,并且我有 2 个带有测试的文件。
在每个文件中我写了以下内容:

// Create the server before each test.
beforeEach(() => {
server = require('../../index');
});

// Close the server after each test.
afterEach(async () => {
if (server) {
server.close();
}
});

index.js 中,我有以下内容(这不是所有代码,而是该错误的相关代码):

// Listen to the server.
const port = config.PORT || process.env.PORT || 3000;
module.exports = app.listen(port, () => {
winston.info(`Listening to port ${port}...`);
});

当我运行 npm test 时我总是遇到这个异常:

**listen EADDRINUSE :::3000**

10 | // Listen to the server
11 | const port = config.PORT || process.env.PORT || 3000;
> 12 | module.exports = app.listen(port, () => {
13 | winston.info(`Listening to port ${port}...`);
14 | });
15 |

我尝试了几种方法来解决这个问题,方法是将 async await 添加到 beforeEachafterEach 中,并尝试将 sever.close 放入afterAllbeforeAll 但仍然出现相同的错误。

然后,我尝试通过这样做来解决:
How Do I Shut Down My Express Server Gracefully When Its Process Is Killed?

但同样,运气不佳。
最后,当我在 1 个文件中编写所有测试时,它在没有这个错误的情况下工作。有人知道如何解决这个问题吗?我不想在 1 个文件中编写我所有的集成测试..
谢谢!

最佳答案

尝试设置 --runInBand 标志,这将按顺序运行您的测试。

https://jestjs.io/docs/en/cli#runinband

在 package.json 脚本中:

"scripts": {
...
"test": "jest --watchAll --verbose --runInBand",
...
}

[更新] 在进一步调查中,虽然您可以使用 --runInBand 按顺序运行测试,但另一种选择是等待 server.close() 因为它返回一个 promise 。因此,在您的 afterEach 中:

...
await server.close();
...

[更新] 我认为解决此问题的更好方法是将 index.js 文件分离为 index.js 和 server.js 文件。这使您能够在没有 .listen 的情况下将 index.js 文件拉入测试:

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

app.get("/", (req, res) => {
res.status(200).send({ hello: "world!" });
});

module.exports = app;

然后在单独的 server.js 文件中:

const server = require("./index");

const PORT = process.env.PORT || 3001;

server.listen(PORT, () => {
console.log(`App running on: ${PORT}`);
});

module.exports = server;

运行您的应用程序时,您运行:node server.js

这使您能够通过将 index.js 文件拉入测试来测试您的路由,如下所示:

// test.js
const request = require("supertest");
const server = require("./index");

describe("GET /", () => {

test("should return status 200", async () => {
const res = await request(server).get("/");
expect(res.status).toBe(200);
});


});

关于node.js - NodeJS:发现错误:听 EADDRINUSE:::3000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51373464/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com