Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

supertest: res.body is not what the Express route sent

Errorres.body does not hold the data the route sent, while res.text does

Short answer

supertest hands you the response through superagent, which fills res.body only for types it can parse (JSON, urlencoded, multipart) and treats 4xx and 5xx as errors. Check res.text and the status first, send an object (not a string) as a JSON body, and never use .end() without passing err to done().

  • Applies to supertest with Jest or Mocha, Express 5, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the three things that decide the body: the status, the content type and the raw text of the response. They show which cause below you have.

    const res = await request(app).get('/api/items');
    console.log(res.status, res.type, res.text);
  2. 2Match what you see, then jump to its fix

    1. 1res.type is text/html (or another non-JSON type) and the data is in res.textThe route does not answer with a type superagent parsesFix
    2. 2The failure message is about the status code, and the body you wanted to read is an error page or an error objectThe route answered 4xx or 5xxFix
    3. 3The route works from a client, but in the test req.body is undefinedThe JSON body was sent as a stringFix
    4. 4The test passes although the body is wrong, or it times outAn assertion inside .end() is not rethrownFix

What does the error look like?

  • res.body does not hold the data the route sent, while res.text does
  • The test fails on the status before the body is ever checked
  • A route that destructures req.body fails, because req.body is undefined
  • A failing .expect() inside .end() does not fail the test

Cause 1 of 4

The route does not answer with a type superagent parses

1Check

superagent parses the types it knows (urlencoded, JSON and multipart) when a parser exists for the response's Content-Type, and exposes the unparsed string as res.text. A route that ends with res.send('...') or returns an HTML page leaves nothing useful in res.body.

console.log(res.type, typeof res.body, res.text);

2Fix

Make the route answer with JSON when it is an API, or assert on res.text when it really returns text. An object given to res.json() or res.send() is sent as JSON.

// route
app.get('/api/items', (req, res) => {
  res.json({ items: [1, 2, 3] });
});

// test
const res = await request(app).get('/api/items').expect(200);
expect(res.body).toEqual({ items: [1, 2, 3] });

3Verify

The test now reads the data from res.body.

console.log(res.type, res.body);

Confirmed by github.com

Did this fix it?

Cause 2 of 4

The route answered 4xx or 5xx

1Check

superagent treats 4xx and 5xx responses (and unhandled 3xx) as errors by default, with the status in err.status and the response in err.response. Look at the status printed in the first step: a 404 or 500 means the route never produced the body.

console.log(res.status, res.text);

2Fix

Fix the route first. If an error status is the expected result, assert that status on purpose and then read the body that came with it.

const res = await request(app)
  .post('/api/items')
  .send({ name: '' })
  .expect(400);
expect(res.body).toHaveProperty('error');

3Verify

The test reaches the body assertion with the status you expected.

npx jest items.test.js

Confirmed by github.com

Did this fix it?

Cause 3 of 4

The JSON body was sent as a string

1Check

superagent sends an object as JSON by default, while a string sent with .send() gets the content type application/x-www-form-urlencoded. express.json() only parses requests whose Content-Type matches application/json, and req.body is undefined when nothing was parsed (in Express 4 it is an empty object).

app.post('/api/items', (req, res) => { console.log(req.get('Content-Type'), req.body); res.sendStatus(204); });

2Fix

Pass the object itself to .send(). If you must send a string, set the JSON content type yourself.

// wrong: a string goes out as urlencoded
await request(app).post('/api/items').send(JSON.stringify({ name: 'pen' }));

// right
await request(app).post('/api/items').send({ name: 'pen' }).expect(201);

// a string with the right header
await request(app)
  .post('/api/items')
  .set('Content-Type', 'application/json')
  .send(JSON.stringify({ name: 'pen' }));

3Verify

The route logs application/json and the parsed object.

npx jest items.test.js

Confirmed by expressjs.com

Did this fix it?

Cause 4 of 4

An assertion inside .end() is not rethrown

1Check

The supertest README says that with .end() a failing .expect() does not throw: to fail the test you must rethrow or pass err to done(). A test that leaves the callback without doing so cannot fail on the body.

grep -rn "\.end(" --include="*.test.js" --exclude-dir=node_modules .

2Fix

Drop .end() and await the request, or pass the error to done().

// async/await
const res = await request(app).get('/api/items').expect(200);

// or with a callback
request(app)
  .get('/api/items')
  .expect(200)
  .end((err, res) => {
    if (err) return done(err);
    expect(res.body.items).toHaveLength(3);
    done();
  });

3Verify

Break the route on purpose; the test now fails.

npx jest items.test.js

Confirmed by github.com

Did this fix it?

How do I stop it coming back?

  • Await every request, and use .expect(status) before you read res.body.
  • Send objects with .send({ ... }) and let superagent set the JSON content type.
  • Give API routes a JSON reply even for errors, so res.body is always readable.
  • Use a custom assertion function that throws when you need to check only some keys of the body.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.