javascriptnode.jsexpressjestjssuperagent

Superagent response body undefined until next line


I am testing my express API using Jest and Supertest. For some reason this does not work:

const id = await request.post('/program')
    .send(body)
    .expect('Content-Type', /json/)
    .expect(201).body.id;

It fails with error:

TypeError: Cannot read property 'id' of undefined

  154 |             sessionId: defaults.authorId
  155 |         };
> 156 |         const id = await request.post('/program')
      |                           ^
  157 |             .send(body)
  158 |             .expect('Content-Type', /json/)
  159 |             .expect(201).body.id;

  at Object.<anonymous> (tests/program.test.js:156:27)

However, just moving the .body.id to the next line fixes the problem.

const res = await request.post('/program')
    .send(body)
    .expect('Content-Type', /json/)
    .expect(201);

const id = res.body.id;

Why is this happening? Is the request not being awaited properly?


Solution

  • In the first case, you are reading the attributes from the return value of expect(201).

    As the return value does not have a body attribute, it crashes when you try to read the id property from it.

    In the second case, you are reading body.id from the response of your server. As you are returning an object with id attribute, you are able to read it.

    If you want to check that your method is returning an object with an id property you can do so with:

    const res = await request.post('/program')
        .send(body)
        .expect('Content-Type', /json/)
        .expect({ id: 201 });