Mock API (API giả lập) là một phiên bản giả của API thực, được tạo ra để mô phỏng hành vi và phản hồi của API thật mà không cần kết nối đến server backend thực tế. Mock API trả về dữ liệu mẫu đã được định nghĩa trước thay vì dữ liệu thực từ database hay các service khác.
Giả sử bạn đang phát triển một ứng dụng quản lý sản phẩm:
API thực:
GET https://api.production.com/products/123
// Phản hồi từ server thực với dữ liệu từ databaseMock API:
GET http://localhost:3000/products/123
// Phản hồi với dữ liệu mẫu đã định nghĩa sẵn
{
"id": 123,
"name": "Laptop Dell XPS 13",
"price": 25000000,
"status": "available"
}Frontend và Backend có thể làm việc độc lập. Team Frontend không cần chờ Backend hoàn thành API để bắt đầu phát triển giao diện.
Ví dụ: Team Frontend cần phát triển trang danh sách đơn hàng, nhưng API /orders chưa sẵn sàng. Họ có thể tạo mock API trả về danh sách đơn hàng mẫu để tiếp tục công việc.
Kiểm thử các component mà không phụ thuộc vào tính sẵn sàng của server thực.
// Test case với Mock API
it('should display product list', async () => {
// Mock API trả về 3 sản phẩm
mockAPI.get('/products').reply(200, [
{ id: 1, name: 'Product 1' },
{ id: 2, name: 'Product 2' },
{ id: 3, name: 'Product 3' }
]);
const products = await getProducts();
expect(products).toHaveLength(3);
});Dễ dàng test các trường hợp lỗi, edge cases mà khó tái tạo với API thực.
// Mock lỗi 500 Internal Server Error
mockAPI.get('/users/999').reply(500, {
error: 'Internal Server Error'
});
// Mock timeout
mockAPI.get('/slow-endpoint').delay(5000).reply(200);
// Mock rate limiting
mockAPI.get('/api/data').reply(429, {
error: 'Too Many Requests'
});- Không cần setup môi trường server phức tạp
- Không tốn chi phí gọi API bên thứ ba
- Không ảnh hưởng đến data production
Tạo demo cho khách hàng hoặc prototype mà không cần backend hoàn chỉnh.
Cách đơn giản nhất để tạo REST API giả với file JSON:
Bước 1: Cài đặt JSON Server
npm install -g json-serverBước 2: Tạo file db.json
{
"products": [
{ "id": 1, "name": "iPhone 15", "price": 999 },
{ "id": 2, "name": "Samsung S24", "price": 899 }
],
"users": [
{ "id": 1, "name": "John Doe", "email": "[email protected]" }
]
}Bước 3: Chạy server
json-server --watch db.json --port 3000Bây giờ bạn có thể gọi:
GET http://localhost:3000/productsPOST http://localhost:3000/productsPUT http://localhost:3000/products/1DELETE http://localhost:3000/products/1
Công cụ mạnh mẽ cho việc mock API trong browser và Node.js:
// Cài đặt MSW
import { rest } from 'msw';
import { setupServer } from 'msw/node';
// Định nghĩa mock handlers
const handlers = [
rest.get('/api/user', (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
username: 'admin',
role: 'administrator'
})
);
}),
rest.post('/api/login', (req, res, ctx) => {
const { username, password } = req.body;
if (username === 'admin' && password === '123456') {
return res(
ctx.status(200),
ctx.json({ token: 'fake-jwt-token' })
);
}
return res(
ctx.status(401),
ctx.json({ error: 'Invalid credentials' })
);
})
];
// Setup server
const server = setupServer(...handlers);
// Sử dụng trong tests
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Postman cung cấp tính năng tạo mock server online:
Bước 1: Tạo Collection trong Postman với các request mẫu
Bước 2: Thêm Example response cho mỗi request
Bước 3: Tạo Mock Server từ Collection
- Click "Create a mock server"
- Chọn Collection
- Postman sẽ tạo URL mock server
Bước 4: Sử dụng mock URL
// Thay vì gọi API thực
fetch('https://api.real.com/users')
// Gọi Mock Server của Postman
fetch('https://123456.mock.pstmn.io/users')// Setup WireMock server
@Rule
public WireMockRule wireMockRule = new WireMockRule(8080);
@Test
public void testGetProduct() {
// Định nghĩa mock response
stubFor(get(urlEqualTo("/products/1"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"id\": 1, \"name\": \"Test Product\"}")));
// Gọi API và verify
Product product = apiClient.getProduct(1);
assertEquals("Test Product", product.getName());
}const nock = require('nock');
// Mock API endpoint
nock('https://api.example.com')
.get('/users/1')
.reply(200, {
id: 1,
name: 'Jane Doe',
email: '[email protected]'
});
// Mock với query parameters
nock('https://api.example.com')
.get('/search')
.query({ q: 'testing' })
.reply(200, [
{ title: 'Testing Guide' },
{ title: 'Testing Best Practices' }
]);
// Mock lỗi network
nock('https://api.example.com')
.get('/unstable')
.replyWithError('Network error');// Tốt ✅
{
"id": "usr_123456",
"email": "[email protected]",
"createdAt": "2024-01-15T10:30:00Z",
"profile": {
"firstName": "John",
"lastName": "Doe",
"avatar": "https://example.com/avatar.jpg"
}
}
// Không tốt ❌
{
"id": 1,
"name": "test"
}mocks/
├── users/
│ ├── valid-user.json
│ ├── invalid-user.json
│ └── user-list.json
├── products/
│ ├── product-detail.json
│ └── product-list.json
└── errors/
├── 404-not-found.json
└── 500-server-error.json
# Mock API Documentation
GET /api/users
Response: 200 OK
Body: Array of users
GET /api/users/{id}
Response: 200 OK | 404 Not Found
Body: User object or error message
POST /api/users
Request: User data without ID
Response: 201 Created
Body: Created user with IDconst faker = require('faker');
function generateMockUser() {
return {
id: faker.datatype.uuid(),
name: faker.name.findName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
address: {
street: faker.address.streetAddress(),
city: faker.address.city(),
country: faker.address.country()
}
};
}
// Tạo 10 users ngẫu nhiên
const mockUsers = Array.from({ length: 10 }, generateMockUser);- Testing End-to-End (E2E): Cần test luồng hoàn chỉnh với API thật
- Performance Testing: Cần đo lường hiệu năng thực tế
- Integration Testing cuối cùng: Verify tích hợp thực sự hoạt động
- Production monitoring: Cần theo dõi API thực trong production
Mock API là công cụ quan trọng trong quy trình phát triển và testing hiện đại. Nó giúp:
- Tăng tốc độ phát triển
- Cải thiện chất lượng testing
- Giảm phụ thuộc giữa các team
- Tiết kiệm chi phí và tài nguyên
Tuy nhiên, cần cân bằng giữa việc sử dụng Mock API và testing với API thực để đảm bảo ứng dụng hoạt động tốt trong môi trường production.