0
0
Expressframework~30 mins

Testing POST with request body in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing POST with request body in Express
📖 Scenario: You are building a simple Express server that accepts user data via a POST request. You want to write a test to check that the server correctly receives and processes the JSON data sent in the request body.
🎯 Goal: Create a test for an Express POST route that sends a JSON body and verifies the server response.
📋 What You'll Learn
Create an Express app with a POST route at /users
Use express.json() middleware to parse JSON request bodies
Write a test that sends a POST request with a JSON body containing {"name": "Alice", "age": 30}
Verify the server responds with status 201 and a JSON message confirming user creation
💡 Why This Matters
🌍 Real World
Testing POST requests with JSON bodies is common when building APIs that accept user data, such as registration forms or data submission endpoints.
💼 Career
Backend developers and QA engineers often write tests like this to ensure API endpoints work correctly and handle data as expected.
Progress0 / 4 steps
1
Set up Express app with POST route
Create an Express app in a variable called app. Add a POST route at /users that responds with status 201 and JSON { message: "User created" }. Use express.json() middleware to parse JSON bodies.
Express
Need a hint?

Remember to use express.json() middleware before defining the POST route.

2
Set up test environment with supertest
Create a variable called request that requires supertest and wraps the app variable for testing HTTP requests.
Express
Need a hint?

Use supertest to wrap your Express app for testing.

3
Write test sending POST request with JSON body
Write an async test function called testCreateUser that sends a POST request to /users with JSON body { name: "Alice", age: 30 } using request.post. Await the response and store it in a variable called response.
Express
Need a hint?

Use request.post('/users').send({ name: "Alice", age: 30 }) and await the response.

4
Verify response status and JSON message
Inside the testCreateUser function, add assertions to check that response.status equals 201 and response.body.message equals "User created".
Express
Need a hint?

Use simple if statements to check response.status and response.body.message.