好的,所以我一直在使用jest和supertest为我的node.js应用程序编写测试,对于第一个之后的每个测试套件,我收到错误Error: listen EADDRINUSE: address already in use :::3000
,我相信这是因为它试图在每次测试时启动服务器文件(我在*.test.js
有多个测试文件/tests
)
在每个测试文件中描述测试之前的顶部看起来像这样
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
使它停止服务器,所以当另一个测试启动它我很好吗?非常感谢。
问题出在这里
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/上阅读更多信息
好吧,所以在每次启动时删除连接并同时使用@Omar Sherif的答案是一个有效的解决方法我发现它不必要地复杂,设置globalSetup每个开玩笑的文档也是一个相当不必要的麻烦。
我发现一个简单的解决方案如下:因为运行jest将NODE_ENV
设置为test,在我的index.js文件夹中,而不是让我的服务器监听不必要的网络端口,我添加了一个非常简单的if条件。
if (process.env.NODE_ENV !== "test") {
app.listen(port, () => console.log(`Server Running on ${port}`));
}
这似乎可以解决问题。谢谢!