Bird
Raised Fist0
Expressframework~10 mins

Testing POST with request body in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Testing POST with request body
Start Test
↓
Send POST request
↓
Server receives request
↓
Parse request body
↓
Process data
↓
Send response
↓
Test checks response
↓
Test Pass or Fail
This flow shows how a POST request with a body is sent, processed by the server, and then tested for the correct response.
Execution Sample
Express
app.use(express.json());

app.post('/data', (req, res) => {
  const { name } = req.body;
  res.json({ greeting: `Hello, ${name}!` });
});
This code defines a POST route that reads 'name' from the request body and responds with a greeting message. Note that express.json() middleware is used to parse JSON bodies.
Execution Table
StepActionRequest BodyServer ProcessingResponse Sent
1Send POST request to /data{"name":"Alice"}Receive request, parse bodyWaiting
2Extract 'name' from body{"name":"Alice"}name = 'Alice'Waiting
3Create greeting message{"name":"Alice"}greeting = 'Hello, Alice!'Waiting
4Send JSON response{"name":"Alice"}Response ready{"greeting":"Hello, Alice!"}
5Test receives response{"name":"Alice"}Response receivedCheck if greeting matches
6Test assertion{"name":"Alice"}Compare expected vs actualPass if matches
💡 Test ends after response is checked and assertion passes or fails.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
req.bodyundefined{"name":"Alice"}{"name":"Alice"}{"name":"Alice"}
nameundefined"Alice""Alice""Alice"
greetingundefinedundefined"Hello, Alice!""Hello, Alice!"
Key Moments - 2 Insights
Why do we need to parse the request body before accessing 'name'?
Because the raw request body is a stream of bytes, parsing converts it into a usable JavaScript object, as shown in step 1 and 2 of the execution_table.
What happens if the request body does not contain 'name'?
The variable 'name' will be undefined, so the greeting will include 'undefined', which can cause unexpected output. This is visible in the variable_tracker if 'name' is missing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'greeting' after step 3?
A"Alice"
B"Hello, Alice!"
Cundefined
D{"name":"Alice"}
💡 Hint
Check the 'Server Processing' and 'Response Sent' columns at step 3 in the execution_table.
At which step does the server send the JSON response back to the client?
AStep 4
BStep 2
CStep 5
DStep 6
💡 Hint
Look for the 'Send JSON response' action in the execution_table.
If the request body was empty, how would the 'name' variable appear in the variable_tracker after step 2?
A"" (empty string)
Bnull
Cundefined
D"name"
💡 Hint
Refer to the variable_tracker row for 'name' and consider what happens if the key is missing in req.body.
Concept Snapshot
POST route receives data in request body
Use middleware to parse JSON body
Access data via req.body.property
Process and send response with res.json()
Test by sending POST with body and checking response
Full Transcript
This visual execution trace shows how to test a POST request with a request body in Express. The test sends a POST request containing JSON data with a 'name' property. The server receives the request, parses the JSON body, extracts the 'name' value, and creates a greeting message. It then sends this greeting back as a JSON response. The test checks the response to confirm it matches the expected greeting. Variables like req.body, name, and greeting change step-by-step as the request is processed. Key moments include understanding why parsing the body is necessary and what happens if expected data is missing. The quiz questions reinforce understanding of variable values and response timing during the process.

Practice

(1/5)
1. What is the main purpose of testing a POST request with a request body in Express?
easy
A. To verify the server correctly receives and processes the sent data
B. To check if the server can handle GET requests
C. To test the server's response time only
D. To confirm the server ignores the request body

Solution

  1. Step 1: Understand POST request role

    POST requests send data to the server, so testing ensures data is received and handled.
  2. Step 2: Identify testing goal

    Testing POST with a body checks if the server processes the data correctly, not just the response time or ignoring data.
  3. Final Answer:

    To verify the server correctly receives and processes the sent data -> Option A
  4. Quick Check:

    POST body testing = verify data handling [OK]
Hint: POST tests check data handling, not just response [OK]
Common Mistakes:
  • Confusing POST with GET request testing
  • Ignoring the request body in tests
  • Testing only response time without data validation
2. Which of the following is the correct way to send JSON data in a POST request test using Supertest in Express?
easy
A. request(app).post('/api').body({ name: 'John' })
B. request(app).post('/api').send({ name: 'John' })
C. request(app).post('/api').query({ name: 'John' })
D. request(app).get('/api').send({ name: 'John' })

Solution

  1. Step 1: Identify correct HTTP method and data sending

    POST requests use .post() and .send() to include JSON body data in Supertest.
  2. Step 2: Evaluate options

    The option with request(app).post('/api').send({ name: 'John' }) uses .post() and .send() correctly. Using .get() is wrong for sending body data. Using .query() sends URL params, not body data. Using .body() is not a Supertest method.
  3. Final Answer:

    request(app).post('/api').send({ name: 'John' }) -> Option B
  4. Quick Check:

    POST + .send() = correct syntax [OK]
Hint: Use .post() with .send() to send JSON body [OK]
Common Mistakes:
  • Using GET instead of POST for sending body data
  • Using .query() instead of .send() for body
  • Trying to use .body() method which doesn't exist
3. Given this Express route and test code, what will be the response body when the test runs?
app.use(express.json());
app.post('/user', (req, res) => {
  res.json({ received: req.body.name });
});

request(app)
  .post('/user')
  .send({ name: 'Alice' })
  .then(res => console.log(res.body));
medium
A. { "received": "Alice" }
B. { "name": "Alice" }
C. {}
D. Error: req.body is undefined

Solution

  1. Step 1: Understand route response

    The route sends back JSON with key 'received' set to req.body.name.
  2. Step 2: Analyze test request body

    The test sends { name: 'Alice' }, so req.body.name is 'Alice'.
  3. Final Answer:

    { "received": "Alice" } -> Option A
  4. Quick Check:

    Response body = { received: 'Alice' } [OK]
Hint: Response echoes req.body.name as 'received' key [OK]
Common Mistakes:
  • Expecting original body instead of transformed response
  • Forgetting to parse JSON body in Express (missing middleware)
  • Assuming empty response or error without middleware
4. You wrote this test for your Express POST route but it fails with an empty req.body. What is the likely cause?
app.post('/data', (req, res) => {
  res.json(req.body);
});

request(app)
  .post('/data')
  .send({ key: 'value' })
  .expect(200, { key: 'value' });
medium
A. The test expects wrong status code
B. Using .send() instead of .query() to send data
C. The route should use GET instead of POST
D. Missing middleware to parse JSON body like express.json()

Solution

  1. Step 1: Identify why req.body is empty

    Express needs middleware like express.json() to parse JSON body; without it, req.body is empty.
  2. Step 2: Check test and route setup

    The test sends JSON with .send(), which is correct; route uses POST correctly; status 200 is expected.
  3. Final Answer:

    Missing middleware to parse JSON body like express.json() -> Option D
  4. Quick Check:

    Missing express.json() = empty req.body [OK]
Hint: Add express.json() middleware to parse JSON body [OK]
Common Mistakes:
  • Not adding express.json() middleware
  • Confusing .send() with .query() for body data
  • Expecting req.body without parsing middleware
5. You want to test an Express POST route that accepts a JSON array in the request body and returns the array length. Which test code correctly sends the array and checks the response?
app.use(express.json());
app.post('/items', (req, res) => {
  res.json({ count: req.body.length });
});
hard
A. request(app).post('/items').send({ length: 3 }).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); });
B. request(app).post('/items').send('{1,2,3}').expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); });
C. request(app).post('/items').send([1, 2, 3]).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); });
D. request(app).post('/items').query([1, 2, 3]).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); });

Solution

  1. Step 1: Understand route expects JSON array body

    The route reads req.body.length, so the body must be an array.
  2. Step 2: Check test sending array correctly

    request(app).post('/items').send([1, 2, 3]).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); }); sends an actual array with .send(), which is correct. request(app).post('/items').send('{1,2,3}').expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); }); sends a string, not JSON array. request(app).post('/items').send({ length: 3 }).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); }); sends an object, not array. request(app).post('/items').query([1, 2, 3]).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); }); uses .query() which sends URL params, not body.
  3. Final Answer:

    request(app).post('/items').send([1, 2, 3]).expect(200).then(res => { if(res.body.count !== 3) throw new Error('Wrong count'); }); -> Option C
  4. Quick Check:

    Send array with .send() to test array length [OK]
Hint: Send array directly with .send() for JSON body tests [OK]
Common Mistakes:
  • Sending array as string instead of JSON
  • Using .query() instead of .send() for body data
  • Sending object with length property instead of array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard