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 await
ed properly?