We test POST requests with a body to make sure our server correctly receives and processes data sent by users or other apps.
0
0
Testing POST with request body in Express
Introduction
When you want to check if your server saves new user info sent via a form.
When you need to verify that your API accepts and handles data correctly.
When you want to confirm that your server responds properly after receiving data.
When you want to catch errors if the data sent is missing or wrong.
When you want to automate testing to avoid manual checks every time you change code.
Syntax
Express
request.post('/path').send({ key: 'value' }).expect(statusCode)
Use .send() to include the request body as an object.
Use testing libraries like supertest with Express to simulate requests.
Examples
Sends a POST request to '/users' with a JSON body containing a name, expecting a 201 Created response.
Express
request.post('/users').send({ name: 'Alice' }).expect(201)
Tests login by sending username and password, expecting a 200 OK response.
Express
request.post('/login').send({ username: 'bob', password: '1234' }).expect(200)
Sample Program
This Express app has a POST route '/greet' that expects a JSON body with a 'name'. The test sends { name: 'Sam' } and expects a 200 response with a greeting message. The test prints the message from the response.
Express
import express from 'express'; import request from 'supertest'; const app = express(); app.use(express.json()); app.post('/greet', (req, res) => { const { name } = req.body; if (!name) { return res.status(400).send({ error: 'Name is required' }); } res.status(200).send({ message: `Hello, ${name}!` }); }); // Test (async () => { const response = await request(app) .post('/greet') .send({ name: 'Sam' }) .expect(200); console.log(response.body.message); })();
OutputSuccess
Important Notes
Always use express.json() middleware to parse JSON bodies in Express.
Use supertest to simulate HTTP requests easily in tests.
Check both status codes and response bodies to ensure your API works as expected.
Summary
Testing POST with a request body ensures your server handles incoming data correctly.
Use .send() to include data in your test requests.
Check both the response status and content to confirm correct behavior.