0
0
Expressframework~30 mins

Supertest for HTTP assertions in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Supertest for HTTP assertions
📖 Scenario: You are building a simple web server using Express. You want to check that your server responds correctly to HTTP requests. This is like testing if a vending machine gives you the right snack when you press a button.
🎯 Goal: Build a small Express server and write tests using Supertest to check the server's responses. You will create the server, set up Supertest, write a test for the home page, and finally add a test for a JSON response.
📋 What You'll Learn
Create an Express app with a GET route at '/' that returns 'Hello World!'
Set up Supertest to test the Express app
Write a test that checks the '/' route returns status 200 and text 'Hello World!'
Add a GET route at '/data' that returns JSON { message: 'Hello JSON' }
Write a test that checks the '/data' route returns status 200 and the correct JSON
💡 Why This Matters
🌍 Real World
Testing web servers ensures they respond correctly before users see them. This prevents bugs and improves reliability.
💼 Career
Backend developers often write tests with Supertest to verify APIs work as expected, which is a key skill in web development jobs.
Progress0 / 4 steps
1
Create Express app with '/' route
Create an Express app in a variable called app. Add a GET route at '/' that sends the text 'Hello World!' as the response.
Express
Need a hint?

Use express() to create the app. Use app.get to add the route. Use res.send to send the text.

2
Set up Supertest for the app
Import supertest and create a variable called request by calling supertest(app). This will let you test the app's routes.
Express
Need a hint?

Import Supertest and call it with app to create request.

3
Write a test for '/' route
Write an async test function called testHomeRoute. Inside, use await request.get('/') to get the response. Check that response.status is 200 and response.text is 'Hello World!'.
Express
Need a hint?

Use await request.get('/') to get the response. Check response.status and response.text with if statements.

4
Add '/data' route and test JSON response
Add a GET route at '/data' that sends JSON { message: 'Hello JSON' }. Then add an async test function called testDataRoute. Use await request.get('/data') and check that response.status is 200 and response.body.message is 'Hello JSON'.
Express
Need a hint?

Add the route with app.get and send JSON with res.json. Write the test like the first one but check response.body.message.