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
Core template-based data generation system that creates realistic mock data using rule syntax and placeholders. Perfect for generating test data, API responses, and development fixtures.
The primary interface for generating mock data from templates.
/**
* Generate mock data from a template
* @param template - Data template with optional generation rules
* @returns Generated mock data matching template structure
*/
Mock.mock(template: any): any;Usage Examples:
// Simple placeholder
const name = Mock.mock('@name');
// Result: "William Anderson"
// Object template
const user = Mock.mock({
id: '@inc',
name: '@name',
email: '@email',
avatar: '@image(200x200)'
});
// Array with rules
const users = Mock.mock({
'data|5-10': [{
'id|+1': 1,
name: '@name',
'age|18-65': 1,
'status|1': ['active', 'inactive']
}]
});Rules control how data is generated and are specified using the | syntax after property names.
// Array rules
'property|count': array // Repeat array items count times
'property|min-max': array // Generate min to max items
'property|1': array // Pick one item randomly
// String rules
'property|count': string // Repeat string count times
'property|min-max': string // Generate min to max length
// Number rules
'property|min-max': number // Generate number in range
'property|min-max.dmin-dmax': number // Float with decimal places
'property|+step': number // Auto-increment by step
// Boolean rules
'property|min-max': boolean // Probability ratio for true/false
'property|probability': boolean // Probability for current value
// Object rules
'property|count': object // Pick count properties randomly
'property|min-max': object // Pick min to max propertiesRule Examples:
const data = Mock.mock({
// Array rules
'list|1-10': [{ name: '@name' }], // 1-10 items
'tags|3': ['javascript', 'node', 'web'], // Pick 3 tags
'categories|2-4': ['tech', 'business'], // 2-4 categories
// String rules
'stars|5': '★', // "★★★★★"
'code|4-8': 'A', // "AAAA" to "AAAAAAAA"
// Number rules
'age|18-65': 1, // Age between 18-65
'price|10-100.2-4': 1, // Price with 2-4 decimals
'id|+1': 1000, // Auto-increment from 1000
// Boolean rules
'active|3-1': true, // 3:1 ratio for true
'featured|1': false, // 1:1 ratio for false
// Object rules
'config|2-3': { // Pick 2-3 properties
debug: true,
logging: false,
cache: true,
compress: false
}
});Placeholders use the @ syntax to generate specific types of random data.
// Basic placeholders
'@boolean' // Random boolean
'@natural' // Natural number (>=0)
'@integer' // Integer
'@float' // Floating point number
'@character' // Single character
'@string' // Random string
// Parameterized placeholders
'@natural(min, max)' // Natural in range
'@integer(min, max)' // Integer in range
'@float(min, max, dmin, dmax)' // Float with decimal control
'@character(pool)' // Character from pool
'@string(pool, min, max)' // String from character pool
// Common data placeholders
'@name' // Full name
'@first' // First name
'@last' // Last name
'@email' // Email address
'@url' // URL
'@ip' // IP address
'@date' // Date string
'@time' // Time string
'@datetime' // DateTime string
'@image' // Image URL
'@color' // Color value
'@title' // Title text
'@sentence' // Sentence
'@paragraph' // Paragraph
'@guid' // GUID/UUIDPlaceholder Examples:
const profile = Mock.mock({
// Personal info
name: '@name', // "Sarah Johnson"
email: '@email', // "sarah.johnson@example.com"
avatar: '@image(100x100)', // Image URL
// Contact details
phone: '@natural(1000000000, 9999999999)',
address: '@city @county', // "Los Angeles County"
// Dates
birthday: '@date(yyyy-MM-dd)', // "1985-07-23"
loginTime: '@datetime', // "2023-04-15 14:30:22"
// Content
bio: '@sentence(10, 20)', // 10-20 word sentence
notes: '@paragraph(2, 4)', // 2-4 sentence paragraph
// IDs
userId: '@guid', // UUID
sessionId: '@string(upper, 8)', // 8 character uppercase
});Internal data template processing engine (available as Mock.Handler).
Mock.Handler: {
/**
* Generate data from template (internal entry point)
* @param template - Data template
* @param name - Property name for context
* @param context - Generation context
* @returns Generated data
*/
gen(template: any, name?: string, context?: any): any;
/**
* Extend objects (utility function)
* @param target - Target object
* @param sources - Source objects to merge
* @returns Extended target object
*/
extend(target: any, ...sources: any[]): any;
// Internal type handlers (for advanced usage)
array(options: HandlerOptions): any[];
object(options: HandlerOptions): any;
number(options: HandlerOptions): number;
boolean(options: HandlerOptions): boolean;
string(options: HandlerOptions): string;
/**
* Process data placeholders (@name, @email, etc.)
* @param placeholder - Placeholder string
* @param obj - Current object context
* @param templateContext - Template context
* @param options - Handler options
* @returns Generated placeholder value
*/
placeholder(placeholder: string, obj: any, templateContext: any, options: HandlerOptions): any;
/**
* Get value by key path for template references
* @param key - Key path (e.g., 'user.id', '../name')
* @param options - Handler options with context
* @returns Value at key path
*/
getValueByKeyPath(key: string, options: HandlerOptions): any;
/**
* Normalize path array for consistent path handling
* @param pathParts - Array of path components
* @returns Normalized path array
*/
normalizePath(pathParts: string[]): string[];
/**
* Split path string into array components
* @param path - Path string (e.g., 'user.profile.name')
* @returns Array of path components
*/
splitPathToArray(path: string): string[];
}
interface HandlerOptions {
type: string;
template: any;
name?: string;
parsedName?: string;
rule?: any;
context?: any;
}Advanced usage with custom context and template references.
// Relative references
const template = {
user: {
id: '@inc',
name: '@name',
email: '@email'
},
posts: [{
authorId: '@user.id', // Reference user.id
title: '@title',
content: '@paragraph'
}]
};
// Function templates
const data = Mock.mock({
timestamp: () => Date.now(),
computed: function() {
return this.id * 2; // Access current context
}
});Complex real-world examples combining multiple features:
// E-commerce product catalog
const productCatalog = Mock.mock({
'categories|3-5': [{
'id|+1': 1,
name: '@title(1, 3)',
slug: '@string(lower, 5, 12)',
'products|5-15': [{
'id|+1': 1000,
name: '@title(2, 5)',
'price|9.99-999.99': 1,
'inStock|3-1': true,
'rating|1-5.1': 1,
'reviews|0-50': 1,
description: '@paragraph(1, 3)',
images: {
'thumbnail': '@image(150x150)',
'gallery|2-5': ['@image(400x400)']
},
'tags|1-4': ['electronics', 'gadget', 'premium', 'bestseller', 'new']
}]
}],
// Pagination info
meta: {
total: '@natural(100, 1000)',
'page|1-10': 1,
'perPage|10': 1,
hasMore: '@boolean'
}
});
// User activity log
const activityLog = Mock.mock({
userId: '@guid',
'activities|10-50': [{
'id|+1': 1,
'type|1': ['login', 'logout', 'purchase', 'view', 'search'],
timestamp: '@datetime(yyyy-MM-dd HH:mm:ss)',
'data': function() {
// Dynamic data based on activity type
const types = {
login: { ip: '@ip', device: '@string(lower, 5, 10)' },
purchase: { amount: '@float(10, 500, 2, 2)', productId: '@natural(1, 1000)' },
search: { query: '@sentence(1, 4)', results: '@natural(0, 100)' },
view: { pageUrl: '@url', duration: '@natural(5, 300)' }
};
return types[this.type] || {};
}
}]
});
// Nested relational data
const blogData = Mock.mock({
'authors|3-8': [{
'id|+1': 1,
name: '@name',
email: '@email',
avatar: '@image(64x64)',
'followers|0-1000': 1
}],
'posts|15-30': [{
'id|+1': 100,
title: '@title(3, 8)',
slug: '@string(lower, 10, 20)',
'authorId|1-8': 1, // References author IDs
content: '@paragraph(5, 15)',
'publishedAt': '@date(yyyy-MM-dd)',
'status|1': ['draft', 'published', 'archived'],
'viewCount|0-10000': 1,
'comments|0-25': [{
'id|+1': 1000,
author: '@name',
email: '@email',
content: '@sentence(5, 30)',
createdAt: '@datetime',
'approved|7-3': true
}],
'tags|1-5': ['javascript', 'web', 'tutorial', 'nodejs', 'react', 'vue', 'angular']
}]
});