Search code examples
automated-testsjestjskoakoa2

Jest timeout testing Koa route


I am starting with Jest for testing our API. However, the moment I add my second test, everything falls apart with a timeout exception.

Here's my code:

const server = require('../server')
const request = require('supertest')
const path = require("path")
const fs = require("fs")
const config = require('../knexfile.js')
const knex = require('knex')(config.development)

beforeAll(async () => {
  let file = fs.readFileSync(path.join(__dirname, '..', 'galaxycard.sql'), 'utf8')
  await knex.raw(file)
  await knex.migrate.latest()
})

afterAll(async () => {
  await knex.raw(`
    DROP SCHEMA public CASCADE;
    CREATE SCHEMA public;
    GRANT ALL ON SCHEMA public TO public;
  `)
  server.close()
})

describe("test 1", () => {
  it("should not be able to add a payment for user without credit", async () => {
    let response = await request(server)
      .post('/v1/hampers')
      .set('Content-Type', 'application/json')
      .send({
        entity_type: 'utility',
        latitude: 1,
        longitude: 1,
        comment: null,
        user_id: new Date().getTime(),
        amount: -200,
        entity_id: 1,
        processed: false
      })
    expect(response.status).toEqual(402)
  })
})

describe("test 2", () => {
  let userId
  beforeEach(async () => {
    userId = new Date().getTime()
    let response = await request(server)
      .post('/v1/hampers')
      .set('Content-Type', 'application/json')
      .send({
        entity_type: 'credit',
        latitude: 0,
        longitude: 0,
        user_id: userId,
        amount: 5000,
        entity_id: 1,
        processed: true
      })
    expect(response.status).toEqual(200)
    expect(JSON.parse(response.text)).toHaveProperty('uuid')
  })

  it("have hampers", async () => {
    let response = await request(server)
      .post('/v1/hampers')
      .set('Content-Type', 'application/json')
      .send({
        entity_type: 'utility',
        latitude: 1,
        longitude: 1,
        comment: null,
        user_id: userId,
        amount: -200,
        entity_id: 1,
        processed: false
      })
    expect(response.status).toEqual(200)
    expect(JSON.parse(response.text)).toHaveProperty('uuid')
  })
})

Jest keeps dying with:

Timeout - Async callback was not invoked within the 5000ms timeout
specified by jest.setTimeout.

Another weird issue is that Jest doesn't exit after the tests have run, even though I use server.close.


Solution

  • The second issue (seeming to hang after the test run) is probably caused by the lack of knex.destroy() in your afterAll. I can speak to the first problem after seeing your route definition.