CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mockjs

JavaScript library for generating random data and intercepting Ajax requests

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

utilities.mddocs/

Utilities

Common utility functions for object manipulation, type checking, string processing, and general-purpose operations. All utilities are available through Mock.Util.

Capabilities

Object Manipulation

Core functions for working with objects and extending their properties.

/**
 * Extend target object with properties from source objects
 * @param target - Target object to extend
 * @param sources - Source objects to merge from
 * @returns Extended target object
 */
Mock.Util.extend(target: any, ...sources: any[]): any;

/**
 * Get all enumerable property keys from object
 * @param obj - Object to get keys from
 * @returns Array of property keys
 */
Mock.Util.keys(obj: any): string[];

/**
 * Get all enumerable property values from object
 * @param obj - Object to get values from
 * @returns Array of property values
 */
Mock.Util.values(obj: any): any[];

Object Examples:

// Extend objects
const target = { a: 1, b: 2 };
const source1 = { b: 3, c: 4 };
const source2 = { c: 5, d: 6 };

const result = Mock.Util.extend(target, source1, source2);
// Result: { a: 1, b: 3, c: 5, d: 6 }

// Get object keys and values
const obj = { name: 'John', age: 30, city: 'NYC' };
const keys = Mock.Util.keys(obj);     // ['name', 'age', 'city']
const values = Mock.Util.values(obj); // ['John', 30, 'NYC']

// Deep extend with nested objects
const deep1 = {
  user: { id: 1, name: 'John' },
  settings: { theme: 'light' }
};
const deep2 = {
  user: { email: 'john@example.com' },
  settings: { language: 'en' }
};

Mock.Util.extend(deep1, deep2);
// Result: {
//   user: { id: 1, name: 'John', email: 'john@example.com' },
//   settings: { theme: 'light', language: 'en' }
// }

Iteration

Functions for iterating over objects, arrays, and other iterable structures.

/**
 * Iterate over object properties or array elements
 * @param obj - Object, array, or number to iterate over
 * @param iterator - Iterator function called for each item
 * @param context - Optional context for iterator function
 */
Mock.Util.each(obj: any, iterator: (value: any, key: any, obj: any) => any, context?: any): void;

Iteration Examples:

// Iterate over array
Mock.Util.each([1, 2, 3], function(value, index) {
  console.log(`${index}: ${value}`);
});
// Output: 0: 1, 1: 2, 2: 3

// Iterate over object
Mock.Util.each({ a: 1, b: 2, c: 3 }, function(value, key) {
  console.log(`${key}: ${value}`);
});
// Output: a: 1, b: 2, c: 3

// Iterate N times (when obj is number)
Mock.Util.each(5, function(value, index) {
  console.log(`Iteration ${index}`);
});
// Output: Iteration 0, Iteration 1, etc.

// Early termination (return false to break)
Mock.Util.each([1, 2, 3, 4, 5], function(value) {
  if (value === 3) return false;  // Break iteration
  console.log(value);
});
// Output: 1, 2 (stops at 3)

// With context
const counter = { count: 0 };
Mock.Util.each([1, 2, 3], function(value) {
  this.count += value;
}, counter);
console.log(counter.count); // 6

Type Checking

Functions for determining and validating data types.

/**
 * Get the type of a value as a lowercase string
 * @param obj - Value to check type of
 * @returns Type string ('string', 'number', 'boolean', 'object', 'array', 'function', 'regexp', 'null', 'undefined')
 */
Mock.Util.type(obj: any): string;

/**
 * Check if value is a string
 * @param obj - Value to check
 * @returns True if string
 */
Mock.Util.isString(obj: any): boolean;

/**
 * Check if value is an object (but not array or null)
 * @param obj - Value to check
 * @returns True if object
 */
Mock.Util.isObject(obj: any): boolean;

/**
 * Check if value is an array
 * @param obj - Value to check
 * @returns True if array
 */
Mock.Util.isArray(obj: any): boolean;

/**
 * Check if value is a regular expression
 * @param obj - Value to check
 * @returns True if RegExp
 */
Mock.Util.isRegExp(obj: any): boolean;

/**
 * Check if value is a function
 * @param obj - Value to check
 * @returns True if function
 */
Mock.Util.isFunction(obj: any): boolean;

/**
 * Check if value is an object or array
 * @param obj - Value to check
 * @returns True if object or array
 */
Mock.Util.isObjectOrArray(obj: any): boolean;

/**
 * Check if value is numeric (can be parsed as number)
 * @param value - Value to check
 * @returns True if numeric
 */
Mock.Util.isNumeric(value: any): boolean;

Type Checking Examples:

// Basic type checking
Mock.Util.type('hello');        // 'string'
Mock.Util.type(123);           // 'number'
Mock.Util.type(true);          // 'boolean'
Mock.Util.type([1, 2, 3]);     // 'array'
Mock.Util.type({a: 1});        // 'object'
Mock.Util.type(null);          // 'null'
Mock.Util.type(undefined);     // 'undefined'
Mock.Util.type(/regex/);       // 'regexp'
Mock.Util.type(function(){});  // 'function'

// Specific type checks
Mock.Util.isString('hello');   // true
Mock.Util.isString(123);       // false

Mock.Util.isArray([1, 2, 3]);  // true
Mock.Util.isArray({});         // false

Mock.Util.isObject({a: 1});    // true
Mock.Util.isObject([1, 2]);    // false
Mock.Util.isObject(null);      // false

Mock.Util.isNumeric('123');    // true
Mock.Util.isNumeric('12.5');   // true
Mock.Util.isNumeric('abc');    // false
Mock.Util.isNumeric(NaN);      // false

// Combined checks
Mock.Util.isObjectOrArray({});     // true
Mock.Util.isObjectOrArray([]);     // true
Mock.Util.isObjectOrArray('str');  // false

String Processing

Utilities for working with multi-line strings and text processing.

/**
 * Extract multi-line string from function comment block
 * @param fn - Function containing /* comment */ block
 * @returns Cleaned multi-line string content
 */
Mock.Util.heredoc(fn: Function): string;

/**
 * No-operation function (does nothing)
 * @returns undefined
 */
Mock.Util.noop(): void;

String Processing Examples:

// Heredoc for multi-line strings
const template = Mock.Util.heredoc(function() {
/*!
<div class="user-card">
  <h3>{{name}}</h3>
  <p>Email: {{email}}</p>
  <p>Age: {{age}}</p>
</div>
*/
});

console.log(template);
// Output:
// <div class="user-card">
//   <h3>{{name}}</h3>
//   <p>Email: {{email}}</p>
//   <p>Age: {{age}}</p>
// </div>

// Use with Mock.js templates
const htmlTemplate = Mock.Util.heredoc(function() {
/*!
<article>
  <h1>{{title}}</h1>
  <p>By {{author}} on {{date}}</p>
  <div>{{content}}</div>
</article>
*/
});

// Generate data to populate template
const articleData = Mock.mock({
  title: '@title(3, 8)',
  author: '@name',
  date: '@date(yyyy-MM-dd)',
  content: '@paragraph(3, 6)'
});

// Replace placeholders with actual data
let populatedHtml = htmlTemplate;
Object.keys(articleData).forEach(key => {
  populatedHtml = populatedHtml.replace(
    new RegExp(`{{${key}}}`, 'g'), 
    articleData[key]
  );
});

Practical Usage Patterns

Common patterns for using Mock.js utilities in real applications.

Data Processing Pipeline:

function processUserData(rawUsers) {
  const processedUsers = [];
  
  Mock.Util.each(rawUsers, function(user, index) {
    // Type validation
    if (!Mock.Util.isObject(user)) {
      console.warn(`User at index ${index} is not an object`);
      return; // Skip invalid user
    }
    
    // Process user data
    const processed = Mock.Util.extend({}, user, {
      id: user.id || Mock.Random.increment(),
      name: Mock.Util.isString(user.name) ? user.name : '@name',
      email: Mock.Util.isString(user.email) ? user.email : '@email',
      createdAt: user.createdAt || Mock.Random.now()
    });
    
    processedUsers.push(processed);
  });
  
  return processedUsers;
}

// Usage
const rawData = [
  { name: 'John', email: 'john@example.com' },
  { name: 'Jane' },  // Missing email
  'invalid',         // Not an object
  { name: 'Bob', email: 'bob@example.com', id: 100 }
];

const processed = processUserData(rawData);
console.log(processed);

Configuration Merging:

function createMockConfig(userConfig) {
  const defaultConfig = {
    timeout: '200-600',
    responseType: 'json',
    headers: {
      'Content-Type': 'application/json'
    },
    debug: false
  };
  
  const finalConfig = Mock.Util.extend({}, defaultConfig, userConfig);
  
  // Validate configuration
  if (!Mock.Util.isString(finalConfig.timeout) && !Mock.Util.isNumeric(finalConfig.timeout)) {
    console.warn('Invalid timeout, using default');
    finalConfig.timeout = defaultConfig.timeout;
  }
  
  return finalConfig;
}

// Usage
const config = createMockConfig({
  timeout: 500,
  debug: true,
  headers: {
    'Authorization': 'Bearer token123'
  }
});

Template Validation Helper:

function validateTemplate(template) {
  const errors = [];
  
  function checkNode(node, path = []) {
    const nodeType = Mock.Util.type(node);
    
    if (Mock.Util.isObject(node)) {
      Mock.Util.each(node, function(value, key) {
        checkNode(value, [...path, key]);
      });
    } else if (Mock.Util.isArray(node)) {
      Mock.Util.each(node, function(value, index) {
        checkNode(value, [...path, index]);
      });
    } else if (Mock.Util.isString(node) && node.startsWith('@')) {
      // Validate placeholder
      if (!node.match(/^@[a-zA-Z][a-zA-Z0-9]*(\([^)]*\))?$/)) {
        errors.push({
          path: path.join('.'),
          message: `Invalid placeholder format: ${node}`
        });
      }
    }
  }
  
  checkNode(template);
  return errors;
}

// Usage
const template = {
  users: [{
    name: '@name',
    email: '@invalid-placeholder',  // Invalid
    age: '@natural(18, 65)'
  }]
};

const validationErrors = validateTemplate(template);
console.log(validationErrors);

docs

ajax-mocking.md

data-generation.md

data-validation.md

index.md

random-data.md

utilities.md

tile.json