Testing APIs helps make sure your app talks correctly with other apps. It finds problems early so users get a smooth experience.
Why testing APIs matters in Express
Introduction
Syntax
Express
const request = require('supertest'); const app = require('./app'); describe('GET /api/data', () => { it('should return data with status 200', async () => { const response = await request(app).get('/api/data'); expect(response.statusCode).toBe(200); expect(response.body).toHaveProperty('data'); }); });
This example uses supertest to test an Express API.
Tests check the status code and response body.
Examples
Express
request(app).get('/api/users').expect(200).then(response => { console.log(response.body); });
Express
request(app).post('/api/login').send({ username: 'user', password: 'pass' }).expect(200);
Express
request(app).get('/api/items/123').expect(404);
Sample Program
This Express app has one API endpoint /api/hello that returns a greeting message in JSON.
The test checks if the endpoint returns status 200 and the correct message.
We run the test manually and print results to the console.
Express
const express = require('express'); const request = require('supertest'); const app = express(); app.use(express.json()); app.get('/api/hello', (req, res) => { res.json({ message: 'Hello, world!' }); }); // Manual test with supertest (async () => { const response = await request(app) .get('/api/hello') .expect(200) .expect({ message: 'Hello, world!' }); console.log(response.statusCode); console.log(response.body); })();
Important Notes
Testing APIs early helps catch bugs before users see them.
Automated tests save time by running checks quickly and often.
Use tools like supertest with Express for easy API testing.
Summary
Testing APIs ensures your app works well with others.
It helps find and fix problems early.
Automated API tests make your development faster and safer.
Practice
1. Why is testing APIs important in Express applications?
easy
Solution
Step 1: Understand the purpose of API testing
Testing APIs helps catch bugs and errors early in development.Step 2: Identify the benefit of early problem detection
Finding problems early prevents issues from reaching users and causing failures.Final Answer:
It helps find and fix problems early before users see them. -> Option CQuick Check:
API testing = early bug detection [OK]
Hint: Testing finds bugs early to avoid user issues [OK]
Common Mistakes:
- Thinking testing speeds up server runtime
- Confusing testing with documentation generation
- Believing testing reduces code size
2. Which of the following is the correct way to write a simple test for an Express API endpoint using a testing library like Jest and Supertest?
easy
Solution
Step 1: Recognize the correct testing syntax
Using Supertest, you call request(app).get('/api') to test the endpoint.Step 2: Confirm chaining with expect and end
The correct pattern chains .expect(200) and .end(done) to complete the test.Final Answer:
request(app).get('/api').expect(200).end(done); -> Option BQuick Check:
Supertest syntax = request(app).get().expect() [OK]
Hint: Supertest uses request(app).get(url).expect(status) [OK]
Common Mistakes:
- Calling expect directly on app.get instead of request
- Swapping app and URL in request call
- Using expect incorrectly without chaining
3. Consider this Express API test snippet using Jest and Supertest:
What will happen if the API returns status 404 instead of 200?
test('GET /users returns 200 and JSON', async () => {
const response = await request(app).get('/users');
expect(response.status).toBe(200);
expect(response.headers['content-type']).toMatch(/json/);
});What will happen if the API returns status 404 instead of 200?
medium
Solution
Step 1: Analyze the status check in the test
The test expects response.status to be exactly 200.Step 2: Understand test behavior on mismatch
If the API returns 404, the expect(response.status).toBe(200) assertion fails and the test fails.Final Answer:
The test will fail because the status is not 200. -> Option AQuick Check:
Status check fails test if not 200 [OK]
Hint: Expect status 200; else test fails [OK]
Common Mistakes:
- Assuming test passes if content-type matches
- Thinking 404 triggers syntax error
- Believing test ignores status mismatch
4. You wrote this Express API test but it always times out:
What is the main reason for the timeout?
test('POST /login returns 200', (done) => {
request(app)
.post('/login')
.send({ username: 'user', password: 'pass' })
.expect(200);
});What is the main reason for the timeout?
medium
Solution
Step 1: Check test callback usage
The test uses done callback but never calls done(), so Jest waits forever.Step 2: Understand how to end async tests
Calling done() inside .end() or returning a promise is needed to finish the test.Final Answer:
Missing call to done() to signal test completion. -> Option AQuick Check:
Call done() to end async test [OK]
Hint: Always call done() or return promise in async tests [OK]
Common Mistakes:
- Forgetting to call done() in callback tests
- Assuming .send() is unsupported
- Guessing wrong HTTP method without checking
5. You want to ensure your Express API handles errors correctly. Which testing approach best helps catch unexpected server errors early?
hard
Solution
Step 1: Identify best practice for error handling tests
Automated tests simulating invalid inputs help verify API returns proper error codes.Step 2: Understand benefits of early automated error detection
This approach finds bugs before deployment and prevents user impact.Final Answer:
Write automated tests that simulate invalid inputs and check for 4xx or 5xx responses. -> Option DQuick Check:
Automated error tests catch bugs early [OK]
Hint: Test invalid inputs automatically to catch errors early [OK]
Common Mistakes:
- Relying only on manual or post-deployment testing
- Ignoring error cases in tests
- Depending on logs instead of tests
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
