Node.JS集成测试错误:侦听EADDRINUSE:地址已在使用中:::3000
我使用和进行集成测试。在每个部分中,我关闭服务器:Node.JS集成测试错误:侦听EADDRINUSE:地址已在使用中:::3000,node.js,jestjs,integration-testing,supertest,Node.js,Jestjs,Integration Testing,Supertest,我使用和进行集成测试。在每个部分中,我关闭服务器: let server; describe('/api/user', () => { beforeEach(() => { server = require('../../../app'); }); afterEach(async () => { await server.close(); }); //some tests }); 但是通过运行npm测试我得到了这个错误: 侦听
let server;
describe('/api/user', () => {
beforeEach(() => {
server = require('../../../app');
});
afterEach(async () => {
await server.close();
});
//some tests
});
但是通过运行npm测试
我得到了这个错误:
侦听EADDRINUSE:地址已在使用中:::3200
当我只使用一个something.test.js文件时,一切都正常。问题是当我添加一个新的something.test.js时。怎么了
以下是package.json:
{
"name": "users",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "jest --watchAll"
},
"author": "Saeed Heidarbozorg",
"license": "ISC",
"dependencies": {
"config": "^3.3.4",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"joi": "^17.4.0",
"morgan": "^1.10.0",
"pg": "^8.5.1",
"winston": "^3.3.3"
},
"devDependencies": {
"jest": "^26.6.3",
"supertest": "^6.1.3"
}
}
tl;dr在测试环境中,您根本不想创建http服务器,只需测试您的express app实例即可 如果你想从你的
app.js
发布你的代码,我可能会给你一个更快的补丁
一般来说,这是我构建它的方式,以便于完成tl;博士:
app.js
包含所有express-y内容:
import express from 'express';
const app = express();
// ... do all your express-y stuff
export default app;
index.js
是启动服务器的应用程序的入口点。测试期间不需要此文件:
import http from 'http';
import app from './app';
http.createServer(app).listen(...);
测试时,您根本不需要index.js
,只需从app.js
导入您的express应用程序并进行测试:
一些测试文件:
import app from './app';
import request from 'supertest';
describe('...',() => {
test('...', async () => {
expect((await request(app).get('/some/route')).status).toBe(200);
});
});