How to run Koa server before Tests in Mocha?

I read a lot of answers to similar questions already but can’t figure out what is wrong in my code.

this is my server.js file

const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()

app.use(require('koa-bodyparser')())

const login = (ctx, next) => {
  ctx.body = ctx.request.body
}

const router = new Router({ prefix: '/api' })

router.get('/test', (ctx, next) => {
  ctx.body = { resp: 'GET REQUEST /test WORKING' }
})
router.post('/login', login)

app.use(router.routes())

module.exports = app

this is my index.js file

const server = require('./server')

server.listen(3000, () => {
  console.log('App is running on http://localhost:3000')
})

and this is my mocha test file

const axios = require('axios').default
const expect = require('chai').expect
const app = require('./server')

describe('7-module-3-task', () => {
  describe('test', function () {
    let server

    before(done => {
      server = app.listen(3000, done)
    })

    after(async () => {
      server.close()
    })

    it('should return response from server', async () => {

      const response = await axios.get('http://localhost:3000/api/test')

      expect(response.data, 'should return object with key "resp').to.have.property('resp')
    })
  })
})

It’s working okay when I make a request in Postman. I tried multiple options already but I still get 404 response, as I understand test is performed before server started running…? How can I make it working ?

Answer

I shared the same code with 2 of my friends and they managed to run tests successfully.

I tested it on my other laptop after this and tests worked as well.

The problem was in the port. 3000 port was used as a default one in the debugger in Webstorm, not sure why but still.

Launching the server on port 3000 in a regular way, not in mocha tests, worked very well but in tests, it did not work, not sure why.

So for those who ever face something similar, check the default port of the debugger or any other built-in server.