-1

I've used jest and supertest for integration tests. In afterEach section I closed server:

let server;
describe('/api/user', () => {
   beforeEach(() => {
      server = require('../../../app');
   });

   afterEach(async () => {
      await server.close();
   });
//some tests
});

But by running npm test I get this error: listen EADDRINUSE: address already in use :::3200

When I using just one something.test.js file, everything is OK. The problem is when I add a new something.test.js. What's wrong?

Here is the 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"
  }
}

1 Answers1

3

tl;dr in a test environment, you don't want to create an http server at all, just test your express app instance.

If you want to post your code from your app.js, I can probably give you a quicker fix.

In general this is the way I structure it to facilitate accomplishing the tl;dr:

app.js contains all the express-y stuff:

import express from 'express';
const app = express();

// ... do all your express-y stuff

export default app;

index.jsis the entry point to the app that starts the server. This file IS NOT NEEDED during testing:

import http from 'http';
import app from './app';

http.createServer(app).listen(...);

When testing, you don't need index.js at all, just import your express app from app.js and test it:

Some test file:

import app from './app';
import request from 'supertest';

describe('...',() => {

   test('...', async () => {
     expect((await request(app).get('/some/route')).status).toBe(200);
   });

});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100