node.jssupertest

What is the purpose/nature of 'done()' in Supertest?


In the (very limited) documentation of Supertest there are code examples where a callback function called done() is passed around:

describe('GET /user', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

What is the purpose/nature of this done() callback?


Solution

  • Your request is asynchronous.

    That means, unless you are able to await it, your function starting in line 2 would exit immediately. Mocha will then proceed with other tests and then suddenly, the request promise would fulfill and do stuff while mocha doesn't even look at your 'responds with json' spec anymore.

    The behavior that you are trying to achieve is to do the request, wait for the response and then test if it is 200.

    There are 2 ways to wait for the response:

    1. done

    By putting done into your function(done) call, the test framework knows that it should wait until done is called before finishing the test.

    1. async
    describe('GET /user', function() {
      it('responds with json', async function() {
        await request(app)
          .get('/user')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200);
      });
    });
    

    Or, (which you can also see in the readme) you can also return the promise, which is the same thing as calling an async function:

    describe('GET /user', function() {
      it('responds with json', function() {
        return request(app)
          .get('/user')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200);
      });
    });