Search code examples
javascriptnode.jsexpressjestjssupertest

Supertest + express setup cause timeout error


I have a simple setup on the server.test.js

import 'regenerator-runtime/runtime';

const request = require('supertest');
const express = require("express")
const app = express();

app.get('/user', function(req, res) {
  res.status(200).json({ name: 'john' });
});

describe('GET /user', function() {
  it('responds with json', async function(done) {
    const response = await request(app)
      .get('/user')
    expect(response.status).toBe(201)
  })
})

npx jest and receive thrown: "Exceeded timeout of 5000 ms for a test., increasing timeout doesn't help in jest.config.js to testTimeout: 20000, it waits for the 20s and also fails

Why express app start with superset? I used an example from the official README


Solution

  • Try to remove done from the test callback:

    it('responds with json', async function() {
      const response = await request(app)
        .get('/user')
      expect(response.status).toBe(201)
    })
    

    Jest may be waiting for it to be called.

    Generally it's recommended that you either use an async function or done. Jest normally warns if you mix them, not sure why it doesn't do so wit this setup.

    Alternatively you can try to call done() at the end of the test.

    You should expect for the test to fail because the status that gets posted is 200 and you are checking for 201.