JavaScript library for generating random data and intercepting Ajax requests
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
XMLHttpRequest interception system for mocking HTTP requests and responses, enabling independent frontend development without backend dependencies. Works with popular Ajax libraries like jQuery, Axios, and native fetch.
Mock HTTP requests by URL patterns with optional method specification.
/**
* Mock HTTP requests by URL pattern
* @param url - Request URL pattern (string or RegExp)
* @param template - Response data template
* @returns Mock instance for chaining
*/
Mock.mock(url: string | RegExp, template: any): typeof Mock;
/**
* Mock HTTP requests by URL pattern and method
* @param url - Request URL pattern (string or RegExp)
* @param method - HTTP method (get, post, put, delete, head, options, patch)
* @param template - Response data template or function
* @returns Mock instance for chaining
*/
Mock.mock(url: string | RegExp, method: string, template: any | Function): typeof Mock;Basic Request Mocking:
// Mock GET request to /api/users
Mock.mock('/api/users', {
'users|5-10': [{
'id|+1': 1,
name: '@name',
email: '@email',
'age|18-65': 1
}]
});
// Mock POST request with specific method
Mock.mock('/api/users', 'post', {
success: true,
message: 'User created successfully',
id: '@inc'
});
// Mock with RegExp pattern
Mock.mock(/\/api\/users\/\d+/, 'get', {
id: '@natural(1, 1000)',
name: '@name',
email: '@email',
avatar: '@image(100x100)'
});Function-based Responses:
// Dynamic response based on request
Mock.mock('/api/search', 'get', function(options) {
// Access request details
console.log(options.url); // Request URL
console.log(options.type); // Request method
console.log(options.body); // Request body
// Return dynamic response
return {
query: options.url.split('q=')[1],
'results|1-20': [{
id: '@guid',
title: '@title',
content: '@paragraph'
}]
};
});
// Simulate different response statuses
Mock.mock('/api/login', 'post', function(options) {
const body = JSON.parse(options.body);
if (body.username === 'admin' && body.password === 'password') {
return {
success: true,
token: '@guid',
user: {
id: 1,
username: 'admin',
role: 'administrator'
}
};
} else {
return {
success: false,
message: 'Invalid credentials'
};
}
});Configure XMLHttpRequest mock behavior globally.
/**
* Configure XMLHttpRequest mock behavior
* @param settings - Configuration options
*/
Mock.setup(settings: {
timeout?: string | number;
}): void;Configuration Examples:
// Set global timeout for mocked requests
Mock.setup({
timeout: '200-600' // Random delay between 200-600ms
});
// Fixed timeout
Mock.setup({
timeout: 400 // 400ms delay
});When using function-based response templates, the options object contains request details.
interface RequestOptions {
url: string; // Request URL
type: string; // HTTP method (GET, POST, etc.)
body: string; // Request body (for POST/PUT)
async: boolean; // Async flag
timeout: number; // Request timeout
headers: object; // Request headers
xhr: XMLHttpRequest; // Original XHR object
}Common patterns for mocking different types of API responses.
REST API Patterns:
// List resources
Mock.mock('/api/posts', 'get', {
'data|10-20': [{
'id|+1': 1,
title: '@title(3, 8)',
content: '@paragraph(2, 5)',
author: '@name',
'tags|1-3': ['javascript', 'web', 'frontend', 'backend'],
publishedAt: '@datetime',
'likes|0-100': 1
}],
total: '@natural(50, 200)',
page: 1,
pageSize: 20
});
// Get single resource
Mock.mock(/\/api\/posts\/\d+/, 'get', {
id: '@natural(1, 1000)',
title: '@title(5, 10)',
content: '@paragraph(5, 15)',
author: {
id: '@natural(1, 100)',
name: '@name',
avatar: '@image(50x50)'
},
'tags|2-5': ['javascript', 'nodejs', 'react', 'vue', 'angular'],
publishedAt: '@datetime',
updatedAt: '@datetime',
'likes|10-500': 1,
'comments|0-50': [{
id: '@natural(1, 10000)',
content: '@sentence(5, 20)',
author: '@name',
createdAt: '@datetime'
}]
});
// Create resource
Mock.mock('/api/posts', 'post', {
success: true,
message: 'Post created successfully',
data: {
id: '@inc',
title: '@title',
slug: '@string(lower, 10, 20)',
createdAt: '@now'
}
});
// Update resource
Mock.mock(/\/api\/posts\/\d+/, 'put', {
success: true,
message: 'Post updated successfully',
updatedAt: '@now'
});
// Delete resource
Mock.mock(/\/api\/posts\/\d+/, 'delete', {
success: true,
message: 'Post deleted successfully'
});Error Response Patterns:
// 404 Not Found
Mock.mock('/api/not-found', 'get', {
error: true,
code: 404,
message: 'Resource not found'
});
// Validation errors
Mock.mock('/api/users', 'post', function(options) {
return {
success: false,
code: 400,
message: 'Validation failed',
errors: {
email: ['Email is required', 'Email format is invalid'],
password: ['Password must be at least 8 characters']
}
};
});
// Server error simulation
Mock.mock('/api/server-error', 'get', {
error: true,
code: 500,
message: 'Internal server error'
});Examples of using Mock.js with popular Ajax libraries.
jQuery Integration:
// Setup mocks
Mock.mock('/api/users', 'get', {
'users|5': [{ id: '@inc', name: '@name' }]
});
// Use with jQuery
$.get('/api/users')
.done(function(data) {
console.log('Users:', data.users);
});Axios Integration:
// Setup mocks
Mock.mock('/api/posts', 'post', {
success: true,
id: '@inc'
});
// Use with Axios
axios.post('/api/posts', { title: 'New Post' })
.then(response => {
console.log('Created:', response.data);
});Fetch API Integration:
// Setup mocks
Mock.mock('/api/data', 'get', {
'items|3-8': [{ id: '@guid', value: '@natural(1, 100)' }]
});
// Use with fetch
fetch('/api/data')
.then(response => response.json())
.then(data => {
console.log('Data:', data.items);
});Internal storage of active mocks (available for inspection).
/**
* Internal registry of active mocks
* Structure: { 'url+method': { rurl, rtype, template } }
*/
Mock._mocked: { [key: string]: MockRule };
interface MockRule {
rurl: string | RegExp; // URL pattern
rtype: string; // HTTP method
template: any | Function; // Response template
}Registry Inspection:
// View active mocks
console.log(Mock._mocked);
// Check specific mock
const usersMock = Mock._mocked['/api/users'];
if (usersMock) {
console.log('Users API is mocked');
}