Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server is not closed when close() is used #1224

Closed
deepj opened this issue Jul 23, 2018 · 4 comments
Closed

Server is not closed when close() is used #1224

deepj opened this issue Jul 23, 2018 · 4 comments
Labels

Comments

@deepj
Copy link

deepj commented Jul 23, 2018

Hello,
I'm trying to write integration test for my first Koa application (I come from Rubyland originally).

I noticed with every new import of my server in my integration tests, the number of request calls inside koa router is increasing. What that means? When I make one call, inside Koa server generates the request multiple times how many times the server is listened.

import app from '../../app'
import tokenSchema from '../../app/schemas/token'
import errorSchema from '../../app/schemas/error'
import {
  createUser,
  truncate,
} from '../helpers'

describe('Authentication API', () => {
  let server

  before(async () => {
    await createUser('tester@email.com')
  })

  beforeEach(() => {
    server = app.listen()
  })

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

  after(async () => {
    await truncate('users')
  })

  describe('POST /auth', () => {
    context('when an user uses valid credentials', () => {
      it('returns authentication token response', async () => {
        const response = await request(server)
          .post('/api/v1/auth')
          .set('Content-Type', 'application/json')
          .send({ email: 'tester@email.com', password: 'password' })

        expect(response.status).to.equal(201)
        expect(response.type).to.equal('application/json')
        expect(response.body).to.be.jsonSchema(tokenSchema)
        expect(response.body.token).to.be.a('string').that.is.not.empty
      })
    })

    context('when an user uses invalid credentials', () => {
      it('returns invalid authentication error', async () => {
        const response = await request(server)
          .post('/api/v1/auth')
          .set('Content-Type', 'application/json')
          .send({ email: 'tester@email.com', password: 'passwrd' })

        expect(response.status).to.equal(401)
        expect(response.type).to.equal('application/json')
        expect(response.body).to.be.jsonSchema(errorSchema)
        expect(response.body).to.deep.equal({
          error: {
            type: 'invalidAuthentication',
            description: 'The credentials are incorrect.',
          },
        })
      })
    })
  })
})
// import server from '../../app/server'
import app from '../../app'
import errorSchema from '../../app/schemas/error'
import {
  createUser,
  truncate,
} from '../helpers'

describe('Users API', () => {
  let server

  beforeEach(() => {
    server = app.listen()
  })

  afterEach(async () => {
    server.close()
    await truncate('users')
  })

  describe('POST /users', () => {
    context('when a given user is not registreted yet', () => {
      it('returns the user response', async () => {
        const response = await request(server)
          .post('/api/v1/users')
          .set('Content-Type', 'application/json')
          .send({ email: 'tester@email.com', password: 'password' })

        expect(response.status).to.equal(201)
        expect(response.type).to.equal('application/json')
        expect(response.body).to.exist
      })
    })
  })
})

When the second spec is called. The request inside Koa route is called twice.

These tests pass but there are other which depends on number of data in DB. I don't know what's wrong.

My app looks

import Koa from 'koa'
import koaBody from 'koa-body'
import logger from 'koa-logger'
import { ENVIRONMENT } from '../config'
import { unprotectedRouter, protectedRouter } from './routes'
import validationErrorsMiddleware from './middlewares/validationErrors'
import internalErrorsMiddleware from './middlewares/internalErrors'
import exceptionsMiddleware from './middlewares/exceptions'
import authorizedErrorsMiddleware from './middlewares/unauthorizedErrors'
import jwtMiddleware from './middlewares/jwt'

const app = new Koa()

if (ENVIRONMENT !== 'test') {
  app.use(logger())
}

app.use(koaBody({
  urlencoded: false,
  text: false,
}))

// Error middlewares
app.use(exceptionsMiddleware)
app.use(internalErrorsMiddleware)
app.use(authorizedErrorsMiddleware)
app.use(validationErrorsMiddleware)

app.use(unprotectedRouter.routes())
app.use(unprotectedRouter.allowedMethods())

app.use(jwtMiddleware)

app.use(protectedRouter.routes())
app.use(protectedRouter.allowedMethods())

export default app

I use the latest koa, mocha, chai, supertest including esm for enabling ES module support. I tried multiple options and this is the latest iteration of that. It looks the server doesn't close after calling close(). In this case, there is no connection made during server initialization so the closing would be fine.

My dependencies:

  "dependencies": {
    "ajv": "^6.5.2",
    "bcrypt": "^3.0.0",
    "camelcase": "^5.0.0",
    "esm": "^3.0.72",
    "firebase-admin": "^5.13.0",
    "jsonwebtoken": "^8.3.0",
    "knex": "^0.15.2",
    "koa": "^2.5.2",
    "koa-body": "^4.0.4",
    "koa-jwt": "^3.3.2",
    "koa-logger": "^3.2.0",
    "koa-router": "^7.4.0",
    "objection": "^1.2.0",
    "objection-db-errors": "^1.0.0",
    "pg": "^7.4.3"
  },
  "devDependencies": {
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "chai-http": "^4.0.0",
    "chai-json-schema-ajv": "^3.0.0",
    "dotenv": "^6.0.0",
    "dotenv-flow": "^0.1.0-beta.3",
    "mocha": "^5.2.0",
    "nodemon": "^1.18.2",
    "sinon": "^6.1.4",
    "sinon-chai": "^3.2.0",
    "supertest": "^3.1.0"
  }
@deepj deepj changed the title Server is not close when close() is used Server is not closed when close() is used Jul 23, 2018
@dicearr
Copy link

dicearr commented Jul 23, 2018

I would recommend you to use request(app.callback());. You can read why in #1064 and #1061.

@fl0w fl0w added the question label Aug 1, 2018
@fl0w
Copy link
Contributor

fl0w commented Aug 1, 2018

I am going to close this as solved. Feel free to reopen if you still have issues with this.

@fl0w fl0w closed this as completed Aug 1, 2018
@deepj
Copy link
Author

deepj commented Aug 1, 2018

@fl0w Thanks. There is any more a problem. I forgot to mention app.callback() helped me. But, there is possible to meantion this in the documentation?
@dicearr Thanks for the tip!

@fl0w
Copy link
Contributor

fl0w commented Aug 1, 2018

@deepj maybe, however this is not a Koa thing. But how node http works and supertest, there's no point for Koa docs to mention all caveats of cross usage of node packages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants