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
Validation system for verifying that real data matches specified Mock.js templates. Perfect for API contract testing, data integrity checks, and ensuring mock data accuracy during development.
Validate data against Mock.js templates to ensure structural and type consistency.
/**
* Validate data against a template schema
* @param template - Mock.js template defining expected structure
* @param data - Real data to validate against template
* @returns Array of validation errors (empty array if valid)
*/
Mock.valid(template: any, data: any): ValidationError[];
interface ValidationError {
path: string[]; // Path to the invalid property
type: string; // Type of validation error
message: string; // Human-readable error message
expected: any; // Expected value or type
actual: any; // Actual value that failed validation
}Basic Validation Examples:
// Valid data
const template = {
name: '@string',
age: '@natural',
active: '@boolean'
};
const validData = {
name: 'John Doe',
age: 25,
active: true
};
const errors = Mock.valid(template, validData);
console.log(errors); // [] - no errors
// Invalid data
const invalidData = {
name: 123, // Should be string
age: 'twenty', // Should be number
active: 'yes' // Should be boolean
};
const errors2 = Mock.valid(template, invalidData);
console.log(errors2);
// [
// { path: ['name'], type: 'type', message: 'Expected string, got number', expected: 'string', actual: 123 },
// { path: ['age'], type: 'type', message: 'Expected number, got string', expected: 'number', actual: 'twenty' },
// { path: ['active'], type: 'type', message: 'Expected boolean, got string', expected: 'boolean', actual: 'yes' }
// ]Validate arrays against templates with generation rules.
// Array template
const listTemplate = {
'items|1-10': [{
id: '@natural',
name: '@string',
'tags|0-3': '@string'
}]
};
// Valid array data
const validArray = {
items: [
{ id: 1, name: 'Item 1', tags: ['tag1', 'tag2'] },
{ id: 2, name: 'Item 2', tags: [] },
{ id: 3, name: 'Item 3', tags: ['tag1'] }
]
};
const arrayErrors = Mock.valid(listTemplate, validArray);
console.log(arrayErrors); // [] - valid
// Invalid array - wrong item structure
const invalidArray = {
items: [
{ id: '1', name: 'Item 1' }, // id should be number
{ name: 'Item 2', tags: 'invalid' } // missing id, tags should be array
]
};
const arrayErrors2 = Mock.valid(listTemplate, invalidArray);
console.log(arrayErrors2);
// Multiple validation errors for array itemsValidate complex nested data structures.
// Nested template
const userTemplate = {
id: '@natural',
profile: {
name: '@string',
contact: {
email: '@email',
phone: '@string'
},
'preferences|0-5': {
theme: '@string',
language: '@string'
}
},
'posts|0-10': [{
id: '@natural',
title: '@string',
'tags|1-5': '@string'
}]
};
// Test nested data
const userData = {
id: 123,
profile: {
name: 'John Smith',
contact: {
email: 'john@example.com',
phone: '+1-555-0123'
},
preferences: {
theme: 'dark',
language: 'en'
}
},
posts: [
{
id: 1,
title: 'My First Post',
tags: ['javascript', 'web']
}
]
};
const nestedErrors = Mock.valid(userTemplate, userData);
console.log(nestedErrors); // Validate nested structureValidate data against specific Mock.js generation rules.
// Template with rules
const rulesTemplate = {
'count|1-100': '@natural', // Should be 1-100
'status|1': ['active', 'inactive'], // Should be one of these values
'rating|1-5.1-2': '@float', // Should be 1-5 with 1-2 decimals
'items|3-8': '@string' // Should have 3-8 items
};
// Test data
const rulesData = {
count: 50, // Valid: within 1-100
status: 'active', // Valid: matches allowed values
rating: 4.5, // Valid: within range with correct decimals
items: ['a', 'b', 'c', 'd', 'e'] // Valid: 5 items within 3-8 range
};
const rulesErrors = Mock.valid(rulesTemplate, rulesData);
console.log(rulesErrors); // Check rule complianceDifferent types of validation errors that can be returned.
// Common error types:
// - 'type': Data type mismatch (string vs number, etc.)
// - 'format': Format validation failure (email, url, etc.)
// - 'range': Numeric value outside expected range
// - 'length': String/array length outside expected bounds
// - 'enum': Value not in allowed enumeration
// - 'required': Missing required property
// - 'structure': Object structure mismatchError Handling Example:
function validateApiResponse(template, response) {
const errors = Mock.valid(template, response);
if (errors.length === 0) {
console.log('✓ API response is valid');
return true;
}
console.log('✗ API response validation failed:');
errors.forEach(error => {
const path = error.path.join('.');
console.log(` ${path}: ${error.message}`);
console.log(` Expected: ${JSON.stringify(error.expected)}`);
console.log(` Actual: ${JSON.stringify(error.actual)}`);
});
return false;
}
// Usage
const apiTemplate = {
success: '@boolean',
'data|1-50': [{
id: '@natural',
name: '@string',
email: '@email'
}]
};
const apiResponse = {
success: true,
data: [
{ id: 1, name: 'John', email: 'john@example.com' },
{ id: 2, name: 'Jane', email: 'invalid-email' } // Invalid email
]
};
validateApiResponse(apiTemplate, apiResponse);Convert Mock.js templates to JSON Schema format for validation.
/**
* Convert Mock.js template to JSON Schema
* @param template - Mock.js template
* @param name - Schema name (optional)
* @param path - Internal path (for recursion)
* @returns JSON Schema object
*/
Mock.toJSONSchema(template: any, name?: string, path?: string[]): JSONSchema;
interface JSONSchema {
name: string;
template: any;
type: string;
rule: ParsedRule;
path: string[];
properties?: JSONSchema[]; // For objects
items?: JSONSchema[]; // For arrays
}
interface ParsedRule {
parameters: any[];
range: boolean;
min: number;
max: number;
count: number;
decimal: boolean;
dmin: number;
dmax: number;
dcount: number;
}Schema Conversion Example:
// Convert template to schema
const template = {
'users|5-10': [{
'id|+1': 1,
name: '@name',
'age|18-65': 1,
active: '@boolean'
}]
};
const schema = Mock.toJSONSchema(template);
console.log(JSON.stringify(schema, null, 2));
// Use schema for validation
const data = {
users: [
{ id: 1, name: 'John', age: 25, active: true },
{ id: 2, name: 'Jane', age: 30, active: false }
]
};
// Validate using the generated schema
const validationErrors = Mock.valid(template, data);Using validation in unit tests and API testing.
// Jest test example
describe('API Response Validation', () => {
const responseTemplate = {
success: '@boolean',
message: '@string',
'data|0-100': [{
id: '@natural',
name: '@string',
email: '@email',
createdAt: '@datetime'
}]
};
test('should validate successful API response', () => {
const response = {
success: true,
message: 'Data retrieved successfully',
data: [
{
id: 123,
name: 'Test User',
email: 'test@example.com',
createdAt: '2023-04-15 10:30:00'
}
]
};
const errors = Mock.valid(responseTemplate, response);
expect(errors).toHaveLength(0);
});
test('should catch invalid API response', () => {
const response = {
success: 'true', // Should be boolean
message: 123, // Should be string
data: 'invalid' // Should be array
};
const errors = Mock.valid(responseTemplate, response);
expect(errors.length).toBeGreaterThan(0);
});
});