开玩笑地尝试多个服务器实例 [英] Multiple server instance attempts while running jest
问题描述
好的,所以我一直在使用jest和supertest为我的node.js应用编写测试,对于第一个之后的每个测试套件,我都会收到错误Error: listen EADDRINUSE: address already in use :::3000
,我相信这是因为它试图启动每个测试文件上的服务器(我在/tests
中有多个测试文件*.test.js
)
Okay, So I've been writing tests for my node.js app using jest and supertest, for every test suite after the first, I'm getting an error Error: listen EADDRINUSE: address already in use :::3000
, I believe this is because it attempts to start the server on every test file (I have multiple test files *.test.js
in /tests
)
每个测试文件中描述测试之前的顶部看起来像这样
The top part before tests are described in each test file looks something like this
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 */
因此,我需要知道如何防止开玩笑尝试初始化服务器的多个实例?是否可以说所有这些代码都在预测试文件中运行?有什么我可以添加到我的afterAll
中以使其停止服务器的功能,所以当另一个测试启动时,我感觉很好吗?非常感谢.
So, I need to know how to prevent jest from attempting to initialize multiple instances of my server? is it possible to say have all this code run in a pre-test file or so? is there something I can add to my afterAll
to cause it to stop the server so when another test starts it i'm good? Many thanks.
推荐答案
好的,因此,在每次启动时删除连接并根据@Omar Sherif的答案同时使用是一个有效的解决方法,我发现它不必要地复杂,可以为每个设置一个globalSetup开玩笑的文档也是一个不必要的麻烦.
Alrighty, so while removing the connection at each start and using concurrently per @Omar Sherif's answer was a valid workaround I found it unnecessarily complicated, setting up a globalSetup per jest's documentation was also a rather unnecessary hassle.
我发现一个简单的解决方案如下:由于运行jest将NODE_ENV
设置为在我的index.js文件夹中进行测试,而不仅仅是让我的服务器监听不必要的网络端口,所以我添加了一个非常简单的if条件.
A simple solution I found was the following; since running jest sets the NODE_ENV
to test, in my index.js folder, instead of just having my server listen to a network port which was unnecessary, I added a very simple if condition.
if (process.env.NODE_ENV !== "test") {
app.listen(port, () => console.log(`Server Running on ${port}`));
}
这似乎可以解决问题.谢谢!
This seemed to do the trick. Thanks!
这篇关于开玩笑地尝试多个服务器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!