Supertest: Error: listen EADDRINUSE: address already in use :::3000

Created on 27 Mar 2019  ยท  32Comments  ยท  Source: visionmedia/supertest

Hey guys, so I have been just trying to start testing my Koa server using Supertest.

I am getting the error: Error: listen EADDRINUSE: address already in use :::3000

I have tried closing everything down on that port and run it but I'm still getting the issue.

Here is my app:

require('dotenv').config();
const Koa = require('koa');
const app = new Koa();
const router = require('./router');
const PORT = process.env.NODE_PORT || 3001;
const ENV = process.env.NODE_ENV || 'Development';
const logger = require('koa-logger');

app.use(logger());
app.use(router.routes());

app.listen(PORT, (err) => {
    if (err) console.error('โŒ Unable to connect the server: ', err);
    console.log(`๐ŸŒ Server listening on port ${PORT} - ${ENV} environment`);
  });

    module.exports = app;

my router:

const Router = require('koa-router');
const router = new Router();

router.get('/', ctx => ctx.body = 'Sending some JSON');
  module.exports = router;

finally the test:

const server = require('../index');
const request = require('supertest').agent(server.listen());

afterEach(() => {
  server.close();
});

describe('routes: index', ()=> {
  it('should reach endpoint', async () => {
    const response = await request(server).get('/');

    expect(response.status).toEqual(200);
    expect(response.body).toEqual('Sending some JSON');
  });
});

my server isn't even running on port 3000 it is running on 8080
however, just to make sure I will run my server on 3000 and it starts up no problem. I then try to run the test, I get the error again with the server running on 3000 and the server not. Kinda stuck

Most helpful comment

lsof -i:3000 
kill -9 [PID] 

All 32 comments

Could you send us the output of:
lsof -i:3000

Hi @rimiti I don't get any output

UPDATE so the reason was because in my app.test.js file I had a series of tests that were not closing after completion because I was running tests like:

const app = require('../index');

describe('server working', () => {

  it('should exist', async (done)=> {
    expect(app).toBeDefined();
    done();
  });

  it('should be an object', async (done)=>{
    expect(typeof app).toBe("object");
    done();
  });
});

and I am _still_ getting the error:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

I had that exact error message, try this out:

Expected: I can use app.listen(PORT, ()=>{})

Code: index.js exports "app", app.listen(PORT, ()=>{}) is uncommented

Output: npm test => "Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue."

Workaround: comment/delete app.listen(PORT) and listen to the port on another file (example: require "app" from index.js in app.js and listen to a port in app.js)

what's weird is that the documentation claims "if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports."

Ok thanks a lot, I will be checking that out for sure!

Looks like you have to do two things:
1) ensure that the app has not yet been started (i.e. put the app.listen in an if statement that asserts it's not in test mode first)
2) pass koa.callback() into supertest as follows:

request(app.callback())
lsof -i:3000 
kill -9 [PID] 

You are actually running the main server in the terminal. Stop the server so the debugger can run on the same PORT

So I had this issue as well.
What you want to do is that you don't want to start your server. In your main server express file you should export the server. But do NOT call the listen method.

So modify your code so that when you're testing (for example by setting an environment variable and looking for that), you're not calling the listen() method. This should resolve it and let you run your tests in parallel.

Thanks a lot @aech12 and @spock123 you saved my day!

Cheers from brazil, thank you all for the support!

lsof -i:3000 
kill -9 [PID] 

What is PID here? New comer please help. Thank you.

@HashemDeveloper when you run lsof -i:3000, you will get some information related to the port. the second column in the returned table says PID, that's what you have to type instead of [PID] when run kill -9

@HashemDeveloper when you run lsof -i:3000, you will get some information related to the port. the second column in the returned table says PID, that's what you have to type instead of [PID] when run kill -9

I actually figured that out by try and error. Thank you for the reply though.

im new to web development and i get the same error and dont know exactly what to do can someone please dumb it down for me

@Abdelrahmanyassin786 In your terminal window, where you are running your application; run this command:
lsof -i:3000
It will return some information related to process running; look for the PID number.
next, run kill -9 [PID], but replace [PID] with the PID number from the first command.
That will kill the process completely, and you will be able to start it again.

it tells me 1sof command is not found

the thing is that my root route doesnt work but if i type for example /blog/new it opens fine

@Abdelrahmanyassin786 It is not a number one it's the letter L

still doesnt work
i wish i would know how to copy my terminal in here like you guys do so i could show you

i tried sth i typed killall -9
then i did killall -u
then killall -v it worked but i honestly dont know which made it work

So I had this issue as well.
What you want to do is that you don't want to start your server. In your main server express file you should export the server. But do NOT call the listen method.

So modify your code so that when you're testing (for example by setting an environment variable and looking for that), you're not calling the listen() method. This should resolve it and let you run your tests in parallel.

@spock123 please do you mean exporting the what i assign the express function to?
For instance
i have
const app = express();

const port = process.env.PORT || 3000;
const server = app.listen(port, () => { console.log(Listening on ${port}.....) });

module.exports = server;

Please do you mean i should export just app??

Hey guys, so I have been just trying to start testing my Koa server using Supertest.

I am getting the error: Error: listen EADDRINUSE: address already in use :::3000

I have tried closing everything down on that port and run it but I'm still getting the issue.

Here is my app:

require('dotenv').config();
const Koa = require('koa');
const app = new Koa();
const router = require('./router');
const PORT = process.env.NODE_PORT || 3001;
const ENV = process.env.NODE_ENV || 'Development';
const logger = require('koa-logger');

app.use(logger());
app.use(router.routes());

app.listen(PORT, (err) => {
    if (err) console.error('โŒ Unable to connect the server: ', err);
    console.log(`๐ŸŒ Server listening on port ${PORT} - ${ENV} environment`);
  });

    module.exports = app;

my router:

const Router = require('koa-router');
const router = new Router();

router.get('/', ctx => ctx.body = 'Sending some JSON');
  module.exports = router;

finally the test:

const server = require('../index');
const request = require('supertest').agent(server.listen());

afterEach(() => {
  server.close();
});

describe('routes: index', ()=> {
  it('should reach endpoint', async () => {
    const response = await request(server).get('/');

    expect(response.status).toEqual(200);
    expect(response.body).toEqual('Sending some JSON');
  });
});

my server isn't even running on port 3000 it is running on 8080
however, just to make sure I will run my server on 3000 and it starts up no problem. I then try to run the test, I get the error again with the server running on 3000 and the server not. Kinda stuck

i experience these problem
root of these problem :
is when i try to run my previous project i created and then i open the server(mix phx.server)
after i run and tried i just close the terminal(MINGW64/MSYS2 terminal) with out killing the running the server(which i don't know how to do it)
after these i create another project and running the server (mix phx.server)
then these problem occurs also in me

my solution to these: i restart my computer and run again then i find it running good again.

but my problem (how to kill the server with out restarting it)

Sometimes, when i press save and the server restarts i get the same error.

I have the same problem and i couldn't understand what do @spock123 and @aech12 mean by exporting the server.
How can you export the server if you are not calling the listen() method, which returns the server object at the first place?
I am really confused, if you can provide a code snippet it would help.
NOTE: I am using --runInBand flag for the moment, it works but it slows down the testing.

module.exports = server;

Please do you mean i should export just app??

Yes! precisely!
You export just the app, but do not call listen()

I have the same problem and i couldn't understand what do @spock123 and @aech12 mean by exporting the server.
How can you export the server if you are not calling the listen() method, which returns the server object at the first place?
I am really confused, if you can provide a code snippet it would help.
NOTE: I am using --runInBand flag for the moment, it works but it slows down the testing.

Hi @zfnori
The server is an instantiation of your application. But only when you call the "listen" method, will it start listening for incoming request.

This means you can export that "server" object like any other variable.
Hope it makes sense.

Sure thing. Thanks a lot

On Tue, Jun 30, 2020, 11:04 PM Lars Rye Jeppesen notifications@github.com
wrote:

module.exports = server;

Please do you mean i should export just app??

Yes! precisely!
You export just the app, but do not call listen()

โ€”
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/visionmedia/supertest/issues/568#issuecomment-652091223,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AJT3CM3LIBKK2KGQIEBUD73RZJVPNANCNFSM4HBWRWDQ
.

I had that exact error message, try this out:

Expected: I can use app.listen(PORT, ()=>{})

Code: index.js exports "app", app.listen(PORT, ()=>{}) is uncommented

Output: npm test => "Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue."

Workaround: comment/delete app.listen(PORT) and listen to the port on another file (example: require "app" from index.js in app.js and listen to a port in app.js)

thankyou @aech12 your solution work for me

I have the same issue, solution that I found is go to node_modules find nodemon/monitor/run. And there is variable "killedAfterChange" in my case var killedAfterChange = false; i changed to var killedAfterChange = true; and it's worked fine

Hi everyon. I had this error:
Error: listen EADDRINUSE: address already in use 3001
The same as above. The problem was in my case colors npm package. I did attach color to the PORT before I passed to the app.listen, like :
const PORT = process.env.PORT.yellow || 5000;
Don't do this,instead use color extension in the console.log, like:
app.listen(PORT, () =>
console.log(
Server running in ${process.env.NODE_ENV.yellow} mode on port ${PORT.yellow}
)
);
Something like this. Hopefully, it helps someone. My issue was solved with this. Happy coding guys! ๐Ÿ™Œ

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Shingaz picture Shingaz  ยท  5Comments

nazreen picture nazreen  ยท  3Comments

EverettQuebral picture EverettQuebral  ยท  3Comments

bookercodes picture bookercodes  ยท  5Comments

peterjuras picture peterjuras  ยท  3Comments