@mahdi.golzar/mockserver
v1.0.0
Published
MockServer is a simple HTTP server designed to simulate APIs during development and testing. It allows you to define custom routes and responses, making it easy to test how your application interacts with an API without needing access to the actual backen
Downloads
8
Readme
MockServer
MockServer is a simple HTTP server designed to simulate APIs during development and testing. It allows you to define custom routes and responses, making it easy to test how your application interacts with an API without needing access to the actual backend.
Features
- Define Routes: Create GET, POST, PUT, DELETE, and other HTTP routes.
- Custom Responses: Return mock data in response to API calls.
- Simulate Network Delays: Introduce artificial delays to simulate real-world network conditions.
- Easy to Start and Stop: Quickly start and stop the mock server for testing purposes.
Installation
No installation is required for this code as it is self-contained and can be added directly to your project.
Usage
- Create a MockServer Instance
const mockServer = new MockServer();
- Define Routes Define custom routes using the on method:
GET Route
mockServer.on('GET', '/api/users', async (req, res) => {
await mockServer.simulateDelay(1000); // Simulate network delay
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify([{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }]));
});
POST Route
mockServer.on('POST', '/api/users', (req, res) => {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const newUser = JSON.parse(body);
newUser.id = Date.now();
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(newUser));
});
});
- Start the Server Start the server on a specified port:
mockServer.start(3000, () => {
console.log('Mock Server is ready to handle requests.');
});
- Stop the Server To stop the server when you're done testing:
mockServer.stop(() => {
console.log('Mock Server has been stopped.');
});