supertest: res.body is not what the Express route sent
res.body does not hold the data the route sent, while res.text doesShort 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().
Fix it fast
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);2Match what you see, then jump to its fix
- 1
res.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
The 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
The route works from a client, but in the test req.body is undefinedThe JSON body was sent as a stringFix - 4
The test passes although the body is wrong, or it times outAn assertion inside .end() is not rethrownFix
- 1
What does the error look like?
res.body does not hold the data the route sent, while res.text doesThe test fails on the status before the body is ever checkedA route that destructures req.body fails, because req.body is undefinedA 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
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.jsConfirmed by github.com
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.jsConfirmed by expressjs.com
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.jsConfirmed by github.com
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
Back end
Express logs [Object: null prototype] instead of a plain object
TypeError: obj.hasOwnProperty is not a function
This is not an error.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix