Mock.js

repository·refactoring·Indexed 12 days ago

https://github.com/nuysoft/mock

A data simulation library for front-end developers to generate mock data based on templates and intercept AJAX requests to simulate back-end responses. Version 1.0.1-beta3 includes a random CLI tool, the Mock.Random utility for generating various data types (including colors, images, and UUIDs), and the Mock.setup() method for XHR interception.

Tokens
3.3K
Snippets
14
Records
17
Agent score
97%

What's inside Mock.js

  1. Overview of Mock.js features

    refactoring

    Mock.js is a simulation data generator designed to help front-end developers prototype and develop independently of back-end progress. It is particularly useful for reducing monotony during automated testing.

    Key capabilities include:

    • Data Generation: Generate simulated data based on specific data templates.
    • Request/Response Mocking: Intercept and provide mock responses for AJAX requests.
  2. Use Mock.Random to generate random data

    refactoring

    The Mock.Random object is a utility class used to generate various types of random data for mocking purposes. It acts as a central hub that aggregates several specialized random data generators through an extension mechanism.

    By using Mock.Random, you can access a wide variety of data types including:

    • Basic: Primitive types like integers, decimals, and booleans.
    • Date: Random dates and timestamps.
    • Image: Random image URLs.
    • Color: Random hex colors.
    • Text: Random strings, sentences, and words.
    • Name: Random names.
    • Web: Random URLs, email addresses, and web-related data.
    • Address: Random physical addresses.
    • Helper/Misc: Various utility and miscellaneous random data generators.
    const Mock = require('mockjs');
    
    // Accessing various random data generators via Mock.Random
    const randomName = Mock.Random.name;
    const randomColor = Mock.Random.color;
    const randomDate = Mock.Random.date;
  3. Initialize Mock.js with setup()

    refactoring

    To intercept XMLHttpRequest (XHR) requests and enable mocking in a browser environment, call Mock.setup(settings). This configures the library to intercept network requests and return mocked data based on your defined rules.

    var Mock = require('mockjs');
    
    Mock.setup({
      // configuration settings
    });
  4. Generate auto-incrementing integers

    refactoring

    The increment() and inc(step) methods provide a way to generate globally unique, auto-incrementing integers, similar to an auto-increment primary key in a database. By default, each call increments the value by 1, but you can provide a custom step value.

    // Default incrementing (starts from 1)
    mock.inc(); // 1
    mock.inc(); // 2
    
    // Custom step incrementing
    mock.inc(5); // 7 (2 + 5)
    mock.inc(10); // 17 (7 + 10)
  5. Access Mock.js core modules

    refactoring

    The Mock object provides access to several utility and core modules for advanced usage:

    • Mock.Handler: Handles the generation and interception logic.
    • Mock.Random: Provides random data generation utilities (e.g., strings, numbers, dates).
    • Mock.Util: General utility functions, including Mock.heredoc for multi-line strings.
    • Mock.XHR: The XMLHttpRequest interception implementation.
    • Mock.RE: Regular expression utilities.
    • Mock.toJSONSchema: Converts data to JSON Schema.
    • Mock.valid: Validation utilities.
  6. Generate mock data with Mock.mock()

    refactoring

    The Mock.mock() method is used to either generate random data based on a template or to intercept specific URL requests. It supports several different invocation patterns:

    1. Generate data from a template: Mock.mock(template) returns the generated data immediately.
    2. Intercept a URL with a template: Mock.mock(rurl, template) intercepts requests to rurl and returns data matching the template.
    3. Intercept a URL with a specific response type: Mock.mock(rurl, rtype, template) allows specifying the response type (e.g., status code or content type) along with the template.
    4. Use a function for dynamic data: Instead of a template, you can pass a function as the second or third argument to generate data dynamically based on request options.

    When intercepting URLs, Mock.mock() returns the Mock instance, allowing for method chaining.

    // 1. Generate data from a template
    var data = Mock.mock({ 'id': '@integer(1, 100)' });
    
    // 2. Intercept XHR requests
    Mock.mock('/api/user', { 'name': 'John Doe' });
    
    // 3. Intercept with response type and template
    Mock.mock('/api/data', 'json', { 'list': '@array(10, 1)' });
    
    // 4. Use a function for dynamic responses
    Mock.mock('/api/dynamic', function(options) {
      return { 'status': 'success', 'data': options.body };
    });
  7. Use the Mock.js RegExp Parser and Handler

    refactoring

    The src/mock/regexp/index.js module provides the core components for parsing and handling regular expressions within the Mock.js ecosystem. It exports two primary classes:

    • Parser: Responsible for parsing regular expression strings.
    • Handler: Responsible for handling the logic associated with the parsed expressions.

    These are typically used internally by Mock.js to generate random data that matches specific regex patterns.

    var RegExpModule = require('mockjs/src/mock/regexp/index.js');
    
    // Access the Parser and Handler
    var Parser = RegExpModule.Parser;
    var Handler = RegExpModule.Handler;
  8. Generate random colors with Mock.js

    refactoring

    The color module provides several methods to generate aesthetically pleasing random colors using the Golden Ratio to ensure visual variety. You can generate colors in various formats including Hex, RGB, RGBA, and HSL.

    Available methods:

    • color(name?): Returns a specific color by name from a dictionary if provided, otherwise returns a random hex color.
    • hex(): Returns a random hex color string (e.g., #DAC0DE).
    • rgb(): Returns a random RGB color string (e.g., rgb(128,255,255)).
    • rgba(): Returns a random RGBA color string with a random alpha channel (e.g., rgba(128,255,255,0.3)).
    • hsl(): Returns a random HSL color string (e.g., hsl(300,80%,90%)).
    const Mock = require('mockjs');
    
    // Random hex color
    Mock.mockMock.random.hex(); // '#DAC0DE'
    
    // Random RGB color
    Mock.mockMock.random.rgb(); // 'rgb(128,255,255)'
    
    // Random RGBA color
    Mock.mockMock.random.rgba(); // 'rgba(128,255,255,0.3)'
    
    // Random HSL color
    Mock.mockMock.random.hsl(); // 'hsl(300,80%,90%)'
    
    // Random color by name (if supported by dictionary)
    Mock.mockMock.random.color('red');
  9. Generate random GUIDs or UUIDs

    refactoring

    Use guid() or uuid() to generate a random Universally Unique Identifier (UUID) string. The format follows the standard pattern of hexadecimal segments separated by hyphens.

    const guid = mock.guid(); // e.g., 'a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6'
    const uuid = mock.uuid(); // Alias for guid()
  10. Generate Base64 image data with `dataImage()`

    refactoring

    The dataImage() method generates a Base64 encoded PNG image string using a canvas. This is useful for client-side rendering without external network requests.

    Behavior:

    • It uses a random brand color from the internal _brandColors collection for the background.
    • The foreground color is hardcoded to #FFF (white).
    • The text displayed is either the provided text argument or the size string if text is undefined.
    • In Node.js environments, this requires the canvas package to be installed (npm install canvas --save).

    Arguments:

    • size: Dimensions in 'widthxheight' format (e.g., '300x250').
    • text: The text to render in the center of the image.
    // Generates a Base64 PNG string
    const base64Image = Random.dataImage('300x200', 'Hello World');
    // Returns: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...' 
  11. Intercept and mock XHR/Ajax requests

    refactoring
    The mock/xhr module provides functionality to intercept and mock XMLHttpRequest (XHR) and Ajax requests. By requiring this module, you can define mock rules that match specific request patterns (URLs, methods, etc.) and return predefined responses, allowing you to simulate backend behavior in client-side environments.