Which of the following is the main reason to test APIs in an Express application?
Think about what testing helps you verify about your API responses and behavior.
Testing APIs helps confirm that endpoints return expected data and handle errors correctly, ensuring reliability and user trust.
Consider an Express API endpoint that is not tested. What is the most likely outcome when a client sends unexpected data?
Think about what happens when code is not checked for handling bad inputs.
Without tests, unexpected inputs can cause crashes or wrong responses because the API behavior is not verified for such cases.
Given the following Express API test using a testing library, what will be the test result?
const request = require('supertest'); const express = require('express'); const app = express(); app.get('/hello', (req, res) => { res.status(200).json({ message: 'Hello World' }); }); describe('GET /hello', () => { it('responds with JSON containing message', async () => { const response = await request(app).get('/hello'); expect(response.status).toBe(200); expect(response.body.message).toBe('Hello World'); }); });
Check the endpoint code and what the test expects.
The endpoint returns status 200 and JSON with message 'Hello World', matching the test expectations, so the test passes.
What is the syntax error in the following Express API test code?
const request = require('supertest'); const app = require('./app'); describe('GET /users', () => { it('should return users list', async () => { const response = await request(app).get('/users'); expect(response.status).toBe(200); expect(response.body).toBeInstanceOf(Array); }); });
Look carefully at the line with the get('/users') call.
The line calling get('/users') is missing a semicolon at the end, which can cause syntax errors in some environments.
Review the following Express API test code. Why does the test fail with a timeout error?
const request = require('supertest'); const express = require('express'); const app = express(); app.get('/data', (req, res) => { // Missing res.send or res.json call }); describe('GET /data', () => { it('should respond with data', async () => { const response = await request(app).get('/data'); expect(response.status).toBe(200); }); });
Check what the endpoint does when it receives a request.
The endpoint handler does not send any response, so the client waits forever and the test times out.