Table of Contents
Developing robust REST APIs requires thorough testing to ensure reliability and correctness. In this article, we will walk through a practical example of building a comprehensive test suite for a TypeScript-based REST API using Supertest. This guide is intended for developers familiar with TypeScript and Node.js who want to improve their testing strategies.
Setting Up the Project
First, create a new Node.js project and install the necessary dependencies:
- Initialize a new project:
npm init -y - Install TypeScript:
npm install typescript --save-dev - Install Express for the API:
npm install express - Install Supertest for testing:
npm install supertest --save-dev - Install types for Node and Express:
npm install @types/node @types/express --save-dev - Create a
tsconfig.jsonfile for TypeScript configuration.
Set up your project structure with folders such as src for source code and tests for test files.
Building a Simple REST API
Create a basic Express server in src/app.ts:
src/app.ts
```typescript
import express from 'express';
const app = express();
app.use(express.json());
let items: string[] = ['apple', 'banana', 'orange'];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
const { item } = req.body;
if (item && typeof item === 'string') {
items.push(item);
res.status(201).json({ message: 'Item added', item });
} else {
res.status(400).json({ error: 'Invalid item' });
}
});
export default app;
And start the server in src/server.ts:
```typescript
import app from './app';
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Writing Tests with Supertest
Create a test file in tests/app.test.ts:
tests/app.test.ts
```typescript
import request from 'supertest';
import app from '../src/app';
describe('API Endpoints', () => {
it('should fetch all items', async () => {
const response = await request(app).get('/items');
expect(response.status).toBe(200);
expect(Array.isArray(response.body)).toBe(true);
expect(response.body).toEqual(['apple', 'banana', 'orange']);
});
it('should add a new item', async () => {
const newItem = 'grape';
const response = await request(app)
.post('/items')
.send({ item: newItem });
expect(response.status).toBe(201);
expect(response.body).toEqual({ message: 'Item added', item: newItem });
});
it('should handle invalid item data', async () => {
const response = await request(app).post('/items').send({ item: 123 });
expect(response.status).toBe(400);
expect(response.body).toHaveProperty('error');
});
});
Running the Tests
Add a script in package.json to run tests:
"scripts": { "test": "jest" }
Install Jest and its TypeScript support:
- npm install jest ts-jest @types/jest --save-dev
- Configure Jest by creating a
jest.config.jsfile.
Run the tests with:
npm test
Conclusion
By following this example, you can set up a testing environment for your TypeScript REST API using Supertest. Regular testing helps catch bugs early and ensures your API performs as expected under various conditions. Expand this test suite by adding more endpoints and edge case tests to improve your application's robustness.