### Install Mock.js in Node.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Install Mock.js using npm for Node.js projects. ```bash npm install mockjs ``` -------------------------------- ### Install Mock.js in Browser Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Include the Mock.js library in your HTML using a script tag. ```html ``` -------------------------------- ### Placeholder Syntax Examples in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/types.md Provides examples of using placeholders for generating dynamic data within strings. Shows direct calls to Random methods, parameterized methods, and path references for absolute and relative data lookups. ```javascript // Direct Random methods 'email': '@EMAIL' 'name': '@NAME' 'age': '@INTEGER(18, 65)' 'birthday': '@DATE("yyyy-MM-dd")' 'guid': '@GUID' // Path references 'userId': '@/id' // Absolute path to root id 'relatedId': '@../id' // Relative path up one level // Custom values 'status': '@status' // Reference to status property in same object ``` -------------------------------- ### Mock.js RegExp Generation Example Source: https://github.com/nuysoft/mock/wiki/Syntax-Specification Demonstrates generating strings that match specified regular expressions using Mock.js. ```javascript Mock.mock({ 'regexp1': /[a-z][A-Z][0-9]/, 'regexp2': /\w\W\s\S\d\D/, 'regexp3': /\d{5,10}/ }) // => { "regexp1": "pJ7", "regexp2": "F)\fp1G", "regexp3": "561659409" } ``` -------------------------------- ### Generate Random Data with Mock.Random Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Use Mock.Random static methods to generate various types of random data. Examples include integers, strings, names, emails, dates, colors, GUIDs, and picking random elements from arrays. ```javascript Mock.Random.integer(1, 100) Mock.Random.string(5) MOCK.Random.name() MOCK.Random.email() MOCK.Random.date('yyyy-MM-dd') MOCK.Random.color() MOCK.Random.guid() MOCK.Random.pick([1, 2, 3]) ``` -------------------------------- ### Simple Function Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md A basic function template that returns a static custom value. ```javascript Mock.mock({ 'computed': function(options) { return 'custom value' } }) ``` -------------------------------- ### Generate Integer Array with Mock.Random.range() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-random.md Creates an array of integers within a specified range. The `start` is inclusive, `stop` is exclusive, and `step` defines the increment. Defaults are applied if `start` and `step` are not provided. ```javascript Mock.Random.range(5) ``` ```javascript Mock.Random.range(2, 8) ``` ```javascript Mock.Random.range(0, 10, 2) ``` ```javascript Mock.Random.range(1, 5, 1) ``` -------------------------------- ### Mock.js Rule Syntax Examples Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md Illustrates common rule syntaxes for generating data in Mock.js, including repetition, range, increment, and decimal place formatting. ```javascript 'propertyName|count': value // Repeat: count times ``` ```javascript 'name|min-max': value // Range: generate between min and max ``` ```javascript 'name|+step': value // Increment: auto-increment by step ``` ```javascript 'name|.dcount': value // Decimal: decimal places ``` ```javascript 'name|dmin-dmax': value // Decimal range: min-max decimal places ``` -------------------------------- ### Mock.js Placeholder Configuration Examples Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/configuration.md Demonstrates standard, custom, and parametric placeholder usage in Mock.js. Placeholders are case-insensitive and can reference other properties or accept custom formats. ```javascript // Standard placeholders (case-insensitive) '@NAME' // Same as @name '@email' // Same as @EMAIL '@Integer(1, 100)' // Same as @INTEGER(1, 100) ``` ```javascript // Custom placeholder by property reference Mock.mock({ 'status': 'active', 'userStatus': '@status' // References 'status' property }) ``` ```javascript // Parametric placeholders '@DATE("yyyy-MM-dd")' // Custom date format '@IMAGE("200x100", "bg", "fg")' // Custom image config ``` -------------------------------- ### String Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Strings can include placeholders that will be replaced with generated data. For example, `'Hello @NAME'` will produce a string with a random name inserted. ```javascript 'Hello @NAME' ``` -------------------------------- ### Simple Computation Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Demonstrates a simple computation within a function template using Handler.gen(). The function returns a random number. ```javascript Handler.gen({ 'value': function(options) { return Math.random() * 100 } }) ``` -------------------------------- ### Mock.js Array Rule Syntax Examples Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md Demonstrates the syntax for applying rules to arrays in Mock.js, such as repeating elements, setting random lengths, and picking random items. ```javascript 'items|count': [{}] ``` ```javascript 'items|min-max': [{}] ``` ```javascript 'method|1': ['GET', 'POST'] ``` ```javascript 'data|+step': [{id: 1}] ``` -------------------------------- ### URL Pattern Examples for Mocking Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Demonstrates various ways to define URL patterns for interception, including exact strings, regular expressions, wildcards, and full URLs with hostnames. ```javascript // Exact match Mock.mock('/api/users', template) ``` ```javascript // Regex match Mock.mock(///api/users/\d+/, template) ``` ```javascript // Wildcard pattern Mock.mock(///api/.*, template) ``` ```javascript // Host + path Mock.mock('http://example.com/api/users', template) ``` ```javascript // With method and regex Mock.mock('GET', ///users/, template) Mock.mock('POST', ///api/.*, template) ``` -------------------------------- ### Sending Request Headers with XMLHttpRequest Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Demonstrates how to set custom request headers like Authorization and X-Custom using XMLHttpRequest before sending a GET request. ```javascript var xhr = new XMLHttpRequest() xhr.open('GET', '/api/users') xhr.setRequestHeader('Authorization', 'Bearer token') xhr.setRequestHeader('X-Custom', 'value') xhr.send() ``` -------------------------------- ### Handler.gen() - Pick Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Demonstrates the pick rule ('|1') with Handler.gen() to select a single random item from a provided array of options. ```javascript // Pick rule: select one Handler.gen({ 'method|1': ['GET', 'POST', 'PUT', 'DELETE'] }) // Result: method is one random value ``` -------------------------------- ### Handler.gen() - With Functions Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Demonstrates using function properties within an object template to compute values based on other properties. ```javascript // With functions Handler.gen({ 'user': { firstName: 'John', lastName: 'Doe', fullName: function(options) { return this.firstName + ' ' + this.lastName } } }) ``` -------------------------------- ### Function Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Functions can be provided to generate dynamic values. The return value of the function will be used as the mock data. ```javascript function() { return value } ``` -------------------------------- ### Setup Global Timeout Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Configure a global timeout for all mocked requests to simulate network latency. This is useful for testing how your application handles delayed responses. ```javascript Mock.setup({ timeout: '200-600' // 200-600ms delay for all mocked requests }) ``` -------------------------------- ### Mock.js Setup with Timeout and Mock Definition Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/configuration.md Configure global mock settings, including response delay, before defining mock data for API endpoints. XHR requests will be delayed according to the specified timeout range. ```javascript // Configure before defining mocks Mock.setup({ timeout: '100-500' }) Mock.mock('/api/users', { 'data|5': [{ 'id|+1': 1, 'name': '@NAME' }] }) // XHR request will be delayed 100-500ms before response ``` -------------------------------- ### Define Mock API Endpoint Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/configuration.md Register a mock for a specific API endpoint. This example shows how to define a mock response for '/api/users'. Mock.setup timeout applies automatically. ```javascript Mock.mock('/api/users', function(options) { // Mock.setup timeout applies automatically // For additional delays, use custom logic return {data: []} }) ``` -------------------------------- ### Mock.js Pass-Through Configuration Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/configuration.md Illustrates how Mock.js handles requests. Non-mocked URLs automatically use the original XMLHttpRequest, while mocked URLs use MockXHR. ```javascript // This URL is NOT mocked - uses real XHR fetch('/real-api/data') // This URL IS mocked - uses MockXHR Mock.mock('/api/data', template) ``` -------------------------------- ### Data with Path References Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Use path references to link data properties within the same mock object. This example links the 'customerId' to the root 'userId'. ```javascript { 'userId': 123, 'order': { 'customerId': '@/userId' } } ``` -------------------------------- ### Get Mock.js Version Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/configuration.md Retrieve the current version of the Mock.js library. No version-specific configuration is available in this release. ```javascript Mock.version // '1.0.1-beta3' ``` -------------------------------- ### Mock.js Number Generation Rules Source: https://github.com/nuysoft/mock/wiki/Syntax-Specification Examples of generating numbers with different rules: automatic increment, integer range, and floating-point numbers with specified decimal precision. ```javascript Mock.mock({ 'number1|1-100.1-10': 1, 'number2|123.1-10': 1, 'number3|123.3': 1, 'number4|123.10': 1.123 }) // => { "number1": 12.92, "number2": 123.51, "number3": 123.777, "number4": 123.1231091814 } ``` -------------------------------- ### Handler.gen() - No Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Demonstrates using Handler.gen() with an array template that has no specific rule. Each template item is processed once. ```javascript // No rule: generate one of each template item Handler.gen({ 'items': [{id: 1}, {id: 2}] }) // Result: items has 2 elements ``` -------------------------------- ### HTTP Method Matching for Mocking Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Specify mock responses for specific HTTP methods. Supported methods include GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH. ```javascript Mock.mock('GET', url, ...) // GET only Mock.mock('POST', url, ...) // POST only // Supported: GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH ``` -------------------------------- ### RegExp Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Regular expressions can be used to generate strings that match the pattern. This is useful for generating IDs or other patterned data. ```javascript /[a-z]+/ ``` -------------------------------- ### Simulating Server Errors with Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Simulates server errors by defining a mock response with an error code and message. This example uses the Fetch API to handle the error response. ```javascript Mock.mock('/api/error', { code: -1, message: 'Server error occurred' }) // Sender fetch('/api/error') .then(res => res.json()) .then(data => { if (data.code !== 0) { throw new Error(data.message) } }) .catch(err => { console.error('Error:', err.message) }) ``` -------------------------------- ### Handler.gen() Usage Examples Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Illustrates direct usage of Handler.gen() for generating mock data, both with and without a provided context object. Typically used indirectly via Mock.mock. ```javascript // Direct use (typically via Mock.mock) var data = Handler.gen({name: '@NAME', age: '@INTEGER(18, 65)'}) ``` ```javascript // With context var data = Handler.gen(template, 'users|5', { currentContext: [], root: [] }) ``` -------------------------------- ### Generate String with Simple RegExp Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Generates a string matching a simple regular expression pattern. Example shows a pattern for three uppercase letters followed by three digits. ```javascript Handler.gen({ 'code': /[A-Z]{3}[0-9]{3}/ }) // Result: 'ABC123' ``` -------------------------------- ### Boolean Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Booleans can be set directly or generated based on probability. Use rules like `|2` to indicate a probability for generating `true`. ```javascript true // Use or probability |2 ``` -------------------------------- ### Mock.setup() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Configures global settings for mock interception, including response delay. ```APIDOC ## Mock.setup() ### Description Configure global settings for mock interception, such as timeout behavior. ### Method ```javascript Mock.setup(settings) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **settings** (object) - Required - Configuration object with timeout and other options - **timeout** (string | number) - Optional - Response delay in milliseconds; can be range (e.g., '10-100') ### Request Example ```javascript Mock.setup({ timeout: '200-600' // Responses delayed 200-600ms }) Mock.setup({ timeout: 500 // Fixed 500ms delay }) ``` ### Response #### Success Response (200) - **settings** (object) - The settings object that was configured. #### Response Example ```json { "timeout": "200-600" } ``` ``` -------------------------------- ### Generate Mock User Profile Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Generates a mock user profile with various data types like ID, GUID, name, email, phone, address, avatar, age, birthday, join date, and active status. ```javascript Mock.mock({ 'id': '@ID', 'guid': '@GUID', 'name': '@NAME', 'email': '@EMAIL', 'phone': /1[3-9]\d{9}/, 'address': '@CITY(true)', 'avatar': '@IMAGE("200x200")', 'age|18-65': 0, 'birthday': '@DATE("yyyy-MM-dd")', 'joined': '@DATE("yyyy-MM-dd HH:mm:ss")', 'active': '@BOOLEAN' }) ``` -------------------------------- ### Placeholder Syntax Overview Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md Illustrates the basic syntax for using placeholders, including function names and path references. ```plaintext @FunctionName @FunctionName() @FunctionName(param1, param2, ...) @path/to/property @../relative/path ``` -------------------------------- ### Conditional Logic in Mock Data Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Implement conditional logic within mock data generation using functions. This example sets the 'price' based on the 'type' property. ```javascript { 'type|1': ['premium', 'standard'], 'price': function() { return this.type === 'premium' ? 99.99 : 9.99 } } ``` -------------------------------- ### Template Rule: Increment Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Generates sequential numbers for 'id' starting from 1 and for 'seq' starting from 100 with increments of 10. ```javascript { 'id|+1': 1, // 1, 2, 3, ... 'seq|+10': 100 // 100, 110, 120, ... } ``` -------------------------------- ### Type Checking and Manipulation with Mock.Util Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Utilize Mock.Util for JavaScript type detection and object manipulation. Examples demonstrate checking types, array instances, and extending objects. ```javascript Mock.Util.type({}) MOCK.Util.isArray([1, 2, 3]) MOCK.Util.extend({a: 1}, {b: 2}) ``` -------------------------------- ### Mock.setup() Configuration Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Configure Mock.js behavior using the `Mock.setup()` method. The `timeout` option can be set to a string range or a number to define the response delay. ```javascript Mock.setup({ timeout: '200-600' // Response delay (string range or number) }) ``` -------------------------------- ### Intercept GET /api/users Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Intercepts GET requests to '/api/users' and returns mock data with a repeating structure. Useful for simulating lists of resources. ```javascript Mock.mock('/api/users', { 'data|5': [{ 'id|+1': 1, 'name': '@NAME', 'email': '@EMAIL' }] }) ``` -------------------------------- ### Intercept GET Requests Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Intercept GET requests to a specific URL and return mocked data defined by a template. Ensure the template is correctly formatted. ```javascript Mock.mock('/api/users', template) ``` -------------------------------- ### Handler.gen() - Increment Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Shows the increment rule ('|+1') with Handler.gen() for cycling through array template items based on the number of calls. Useful for sequential data generation. ```javascript // Increment rule: cycle through Handler.gen({ 'items|+1': [ {id: 1, name: 'First'}, {id: 2, name: 'Second'}, {id: 3, name: 'Third'} ] }) // First call: First item, second call: Second item, etc. ``` -------------------------------- ### Jest/Mocha Setup and Usage with Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Configure Mock.js for testing by setting a timeout and then mock API endpoints within your tests. This is useful for simulating backend responses during frontend development and testing. ```javascript // Setup before tests beforeEach(function() { Mock.setup({timeout: 0}) // No delay for tests }) // Use in tests it('should fetch users', function(done) { Mock.mock('/api/users', { 'data|5': [{id|+1: 1, name: '@NAME'}] }) fetch('/api/users') .then(res => res.json()) .then(data => { expect(data.data.length).toBe(5) done() }) }) ``` -------------------------------- ### Get Object Values with Util.values() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/utilities.md Use Util.values() to get an array containing the values of an object's own properties. It excludes inherited property values. ```javascript Mock.Util.values({a: 1, b: 2, c: 3}) // [1, 2, 3] Mock.Util.values({}) // [] ``` -------------------------------- ### Mock.setup(settings) Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Configures global options for the Mock API, such as request timeout. ```APIDOC ## Mock.setup(settings) ### Description Configures global options for the Mock API. ### Method ```javascript Mock.setup(settings) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **settings** (object) - Required - An object containing configuration settings. Example: `{timeout: '100-500'}`. ``` -------------------------------- ### Get Type of Value with Util.type() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/utilities.md Use Util.type() to get the lowercase type name of any JavaScript value. It supports primitive types, arrays, objects, functions, and regular expressions. ```javascript Mock.Util.type('hello') // 'string' Mock.Util.type(123) // 'number' Mock.Util.type([]) // 'array' Mock.Util.type({}) // 'object' Mock.Util.type(function() {}) // 'function' Mock.Util.type(/regex/) // 'regexp' Mock.Util.type(true) // 'boolean' Mock.Util.type(null) // 'null' Mock.Util.type(undefined) // 'undefined' ``` -------------------------------- ### Configure Global Mock Settings Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Use Mock.setup() to configure global settings for mock interception, such as response delay. The timeout can be a fixed number of milliseconds or a range. ```javascript Mock.setup({ timeout: '200-600' }) ``` ```javascript Mock.setup({ timeout: 500 }) ``` -------------------------------- ### Using Random Functions in Mock Templates Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-random.md Demonstrates how to use various random data generation functions like @NAME, @EMAIL, @INTEGER, @DATE, @IMAGE, @COLOR, @PHONE, @CITY, and @GUID within a mock template. These functions are called using the '@FUNCTION_NAME' syntax. Function names are case-insensitive. ```javascript Mock.mock({ 'id|+1': 1, 'name': '@NAME', 'email': '@EMAIL', 'age': '@INTEGER(18, 65)', 'birthday': '@DATE("yyyy-MM-dd")', 'avatar': '@IMAGE("200x200")', 'color': '@COLOR', 'phone': '@PHONE', 'address': '@CITY(true)', 'guid': '@GUID' }) ``` -------------------------------- ### Import Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Import the Mock.js library. Use `require` in Node.js environments or access `window.Mock` in browsers. ```javascript var Mock = require('mockjs') // or window.Mock in browser ``` -------------------------------- ### Path References for Mock Data Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Use path references starting with '@' to specify where mock data should be sourced from. This includes absolute paths from the root, relative paths to the parent, or referencing properties at the same level. ```javascript '@/absolutePath' // From root '@../relativePath' // Relative to parent '@propertyName' // Same-level property ``` -------------------------------- ### Handler.gen() - Range Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Illustrates using Handler.gen() with a range rule ('|3-8') to generate a random number of items between the specified minimum and maximum. Uses '@NAME' for item content. ```javascript // Range rule: 3-8 items Handler.gen({ 'items|3-8': [{name: '@NAME'}] }) // Result: items has 3-8 generated items ``` -------------------------------- ### Handler.gen() - No Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Processes all properties of an object template when no specific rule is applied. ```javascript // No rule: process all properties Handler.gen({ 'user': { name: '@NAME', email: '@EMAIL', age: '@INTEGER(18, 65)' } }) ``` -------------------------------- ### Mock.setup(settings) Source: https://github.com/nuysoft/mock/wiki/Mock.setup() Configures the behavior of intercepted Ajax requests. The supported configuration item is 'timeout'. ```APIDOC ## Mock.setup( settings ) ### Description Configures the behavior of intercepted Ajax requests. Supports the configuration item `timeout`. ### Parameters #### settings - **settings** (Object) - Required - A collection of configuration items. #### timeout - **timeout** (Number | String) - Optional - Specifies the response time for intercepted Ajax requests, in milliseconds. Can be a positive integer (e.g., `400`) or a string in a hyphen-separated format (e.g., `'200-600'`). Defaults to `'10-100'`. ### Request Example ```javascript Mock.setup({ timeout: 400 }) Mock.setup({ timeout: '200-600' }) ``` ### Notes Currently, the `Mock.setup( settings )` interface is only used to configure Ajax requests and may be used to configure other behaviors of Mock in the future. ``` -------------------------------- ### Relative Path Reference Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md Reference a sibling property using a relative path starting with '@../'. ```javascript Mock.mock({ 'firstName': 'John', 'lastName': 'Doe', 'profile': { 'ownerName': '@../firstName' // References sibling firstName } }) ``` -------------------------------- ### Absolute Path Reference Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/template-syntax.md Reference a property at the root of the mock object using an absolute path starting with '@'. ```javascript Mock.mock({ 'id': 1, 'data': { 'userId': '@/id' // References root id } }) ``` -------------------------------- ### Using Options in Function Template Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Illustrates how to access the `options` parameter within a function template, specifically using `options.context.path` to construct a string. ```javascript Handler.gen({ 'item': function(options) { // options.name = property name with rule // options.context.path = current path return 'Item ' + options.context.path.join('.') } }) ``` -------------------------------- ### Generate Mock Product Data Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Generates mock product data including ID, SKU, name, description, price, stock, category, image, creation date, rating, and reviews. ```javascript Mock.mock({ 'id|+1': 1, 'sku': /[A-Z]{3}\d{6}/, 'name': '@TITLE', 'description': '@SENTENCE', 'price|99-9999.2': 0, 'stock|0-1000': 0, 'category|1': ['Electronics', 'Clothing', 'Books'], 'image': '@IMAGE', 'created': '@NOW("yyyy-MM-dd HH:mm:ss")', 'rating|1-5': 0, 'reviews|0-20': [] }) ``` -------------------------------- ### Mock.mock(url, template) Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Intercepts GET requests to a specified URL and returns mocked data based on the template. ```APIDOC ## Mock.mock(url, template) ### Description Intercepts GET requests to a specified URL and returns mocked data. ### Method ```javascript Mock.mock(url, template) ``` ### Endpoint `/api/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **url** (string) - Required - The URL to intercept. * **template** (object) - Required - The template object used to generate mock data. ``` -------------------------------- ### Handler.gen() - Min-Max Rule Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Randomly selects a specified number of properties (between min and max) from an object template. ```javascript // Min-max rule: select 2-4 properties Handler.gen({ 'user|2-4': { name: '@NAME', email: '@EMAIL', phone: '@PHONE', address: '@ADDRESS' } }) ``` -------------------------------- ### String Generation Rules in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/types.md Shows how to apply rules to strings for repetition and random generation. Includes repeating a string a fixed number of times, generating a variable number of repetitions, and using placeholders for dynamic content. ```javascript // Repeat string 3 times 'stars|3': '★' // Generate 1-5 repetitions 'text|1-5': '@WORD' // String is treated as template 'email|1': '@EMAIL' ``` -------------------------------- ### Mock List with Metadata Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Generate a mock list of items, each with an ID, title, creation date, and tags. It also includes metadata like total count and fetch timestamp, demonstrating dynamic data generation. ```javascript Mock.mock('/api/items', { 'items|5-20': [{ 'id|+1': 1, 'title': '@TITLE', 'created': '@NOW("yyyy-MM-dd")', 'tags|1-3': ['@WORD'] }], 'total': function() { return this.items.length }, 'fetched': '@NOW("yyyy-MM-dd HH:mm:ss")' }) ``` -------------------------------- ### Generate Mock Blog Post Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Generates a mock blog post with title, slug, author details, content, tags, publication/update dates, views, and comments. ```javascript Mock.mock({ 'id|+1': 1, 'title': '@TITLE', 'slug': function() { return this.title.toLowerCase().replace(/\s+/g, '-') }, 'author': { 'name': '@NAME', 'email': '@EMAIL' }, 'content': '@PARAGRAPH(5)', 'tags|2-5': ['@WORD'], 'published': '@NOW("yyyy-MM-dd")', 'updated': '@NOW("yyyy-MM-dd HH:mm:ss")', 'views|0-100000': 0, 'comments|0-50': [{ 'id|+1': 1, 'author': '@NAME', 'text': '@SENTENCE', 'date': '@DATE("yyyy-MM-dd HH:mm:ss")' }] }) ``` -------------------------------- ### Context-Dependent Response with URL Parameters Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Mocks a GET request for '/api/users/:id' and extracts the ID from the URL to customize the response data. ```javascript Mock.mock('GET', '/api/users/:id', function(options) { // Extract ID from URL var urlMatch = options.url.match(/\/users\/(\d+)/) var userId = urlMatch ? urlMatch[1] : null return { code: 0, data: { id: userId, name: '@NAME', email: '@EMAIL' } } }) ``` -------------------------------- ### Testing Mocked and Real APIs Simultaneously Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Shows how to configure a mock for a specific URL while allowing other URLs to make real network requests using the Fetch API. ```javascript Mock.mock('/api/mock', template) // Real request fetch('/real-endpoint') .then(res => res.json()) .then(data => console.log('Real:', data)) // Mocked request fetch('/api/mock') .then(res => res.json()) .then(data => console.log('Mocked:', data)) ``` -------------------------------- ### Get Object Keys with Util.keys() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/utilities.md Use Util.keys() to retrieve an array of an object's own property names. It does not include inherited properties. ```javascript Mock.Util.keys({a: 1, b: 2}) // ['a', 'b'] Mock.Util.keys({}) // [] ``` -------------------------------- ### Configure RequireJS Paths for Mock Source: https://github.com/nuysoft/mock/blob/refactoring/test/test.mock.html Sets up module paths for 'mock', 'jquery', and 'underscore' using RequireJS. This is necessary for loading mock-related modules and their dependencies. ```javascript window.require = window.requirejs; require.config({ paths: { 'mock': '../dist/mock', 'jquery': 'https://unpkg.com/jquery@2.2.4/dist/jquery', 'underscore': 'https://unpkg.com/underscore@1.9.1/underscore' } }) ``` -------------------------------- ### Mock.XHR.setup Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Configures the XMLHttpRequest interceptor with specified settings. This method allows customization of XHR timeout and other behaviors for mocking purposes. ```APIDOC ## Mock.XHR.setup(settings) ### Description Configure XHR timeout and behavior. ### Method POST ### Endpoint /mock/xhr/setup ### Parameters #### Query Parameters - **settings** (object) - Required - Configuration object for XHR behavior. ``` -------------------------------- ### Advanced Utility Patterns Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/utilities.md Demonstrates advanced utility functions for type checking, configuration merging, and iteration. ```APIDOC ## Advanced Utility Patterns ### Combining Utilities ```javascript // Type checking with isArray/isObject var isComplex = Mock.Util.isArray(val) || Mock.Util.isObject(val) // Deep merging configs var config = Mock.Util.extend( {debug: false, timeout: 100}, userConfig ) // Iterating and transforming var doubled = [] Mock.Util.each([1, 2, 3], function(val) { doubled.push(val * 2) }) // Checking multiple types var isIterable = Mock.Util.type(val).match(/array|object/) !== null ``` ``` -------------------------------- ### Object Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Objects are processed recursively. Use this to define nested structures where properties can themselves be mock placeholders or other objects. ```javascript {id: 1, name: '@NAME'} ``` -------------------------------- ### Generate Random Email with Mock.Random Source: https://github.com/nuysoft/mock/wiki/Mock.Random Demonstrates how to generate a random email address using Mock.Random.email() and how to use it within Mock.mock() with placeholder syntax. ```javascript var Random = Mock.Random Random.email() // => "n.clark@miller.io" Mock.mock('@email') // => "y.lee@lewis.org" Mock.mock( { email: '@email' } ) // => { email: "v.lewis@hall.gov" } ``` -------------------------------- ### Number Increment Rule Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Generate sequential numbers starting from the given value, incrementing by 1 for each subsequent item, using the `\|+1` syntax. ```javascript 'id\|+1': 1 ``` -------------------------------- ### Util.type() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/utilities.md Get the lowercase type name of a given value. It supports various primitive types, arrays, objects, functions, and regular expressions. ```APIDOC ## Util.type() ### Description Get lowercase type name of a value. ### Method Util.type(obj) ### Parameters #### Path Parameters - **obj** (any) - Required - Value to check ### Returns Lowercase type string ### Supported Types | Type | Return Value | |------|-------------| | String | 'string' | | Number | 'number' | | Boolean | 'boolean' | | Array | 'array' | | Object (plain) | 'object' | | Function | 'function' | | RegExp | 'regexp' | | null | 'null' | | undefined | 'undefined' | ### Usage Examples ```javascript Mock.Util.type('hello') // 'string' Mock.Util.type(123) // 'number' Mock.Util.type([]) // 'array' Mock.Util.type({}) // 'object' Mock.Util.type(function() {}) // 'function' Mock.Util.type(/regex/) // 'regexp' Mock.Util.type(true) // 'boolean' Mock.Util.type(null) // 'null' Mock.Util.type(undefined) // 'undefined' ``` ``` -------------------------------- ### Mock.js Data Placeholder Usage Source: https://github.com/nuysoft/mock/wiki/Syntax-Specification Illustrates how to use placeholders like '@FIRST', '@LAST', and custom combinations within a data template to generate dynamic values. ```javascript Mock.mock({ name: { first: '@FIRST', middle: '@FIRST', last: '@LAST', full: '@first @middle @last' } }) // => { "name": { "first": "Charles", "middle": "Brenda", "last": "Lopez", "full": "Charles Brenda Lopez" } } ``` -------------------------------- ### Boolean Generation Rules in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/types.md Explains rules for generating boolean values with probabilities. Demonstrates setting a higher probability for 'true' and specifying a probability range. ```javascript // True with 2x probability vs false 'active|2': true // True with 1/4 probability 'flag|1-3': true ``` -------------------------------- ### Method-Specific AJAX Interception Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Mock different responses based on the HTTP method (GET, POST, PUT, DELETE) for a given API endpoint. ```javascript // GET request Mock.mock('GET', '/api/users', { 'data|5': [{ 'id': '@ID', 'name': '@NAME' }] }) // POST request Mock.mock('POST', '/api/users', function(options) { return { code: 0, message: 'Created', id: Mock.Random.id() } }) // PUT request Mock.mock('PUT', '/api/users/:id', { code: 0, message: 'Updated' }) // DELETE request Mock.mock('DELETE', '/api/users/:id', { code: 0, message: 'Deleted' }) ``` -------------------------------- ### Handler.string() Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/handler.md Handles string templates, supporting placeholder replacement, repetition rules, and path references. ```APIDOC ## Handler.string() ### Description Processes string templates with repetition and placeholders. ### Method Signature ```javascript Handler.string(options) ``` ### Options Parameter ```json { "type": "string", "template": "string", "rule": "object", "context": "object" } ``` ### Returns Generated string (or type-converted if single placeholder). ### Behavior 1. Applies repetition rules based on the provided rule. 2. Replaces placeholders (e.g., `@NAME`, `@EMAIL`, `@/path`) within the string. 3. If the template is a single placeholder and no rule is applied, the value is type-converted. ### Placeholder Examples - `@NAME`: Replaced with a generated name. - `@EMAIL`: Replaced with a generated email. - `@WORD(5)`: Replaced with a 5-character word. - `@/id`: Absolute path reference. - `@../status`: Relative path reference. - `@property`: Reference to a same-level property. - `\@escaped`: Literal '@escaped'. ``` -------------------------------- ### Mocking JSON Body Requests Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Intercepts POST requests to '/api/users' and parses the JSON body. Includes an example of sending JSON data using XMLHttpRequest. ```javascript Mock.mock('POST', '/api/users', function(options) { var body = JSON.parse(options.body) return { code: 0, message: 'Created', data: { id: Mock.Random.id(), ...body } } }) ``` ```javascript // Sender var xhr = new XMLHttpRequest() xhr.open('POST', '/api/users') xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify({ name: 'John', email: 'john@example.com' })) ``` -------------------------------- ### Array Generation Rules in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/types.md Demonstrates various rules for generating arrays and their elements. Includes picking random items, generating a range of items, specifying an exact count, and auto-incrementing values within array elements. ```javascript // Pick 1 random item 'method|1': ['GET', 'POST', 'DELETE'] // Generate 1-10 items 'data|1-10': [{id: 1, name: '@NAME'}] // Generate exactly 5 items 'items|5': ['item'] // Auto-increment through array with +step 'users|+1': [{id: 1, name: '@NAME'}] ``` -------------------------------- ### Mocking HTTP Status Codes with Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Illustrates how to use Mock.js to simulate various HTTP status codes by defining them within the response body. This is useful for testing client-side error handling. ```javascript // Success Mock.mock('/api/users', {code: 0, data: []}) // 200 OK // Client errors Mock.mock('/api/users', {code: 400, message: 'Bad request'}) // 400 Mock.mock('/api/users', {code: 401, message: 'Unauthorized'}) // 401 Mock.mock('/api/users', {code: 403, message: 'Forbidden'}) // 403 Mock.mock('/api/users', {code: 404, message: 'Not found'}) // 404 // Server errors Mock.mock('/api/users', {code: 500, message: 'Server error'}) // 500 Mock.mock('/api/users', {code: 503, message: 'Service unavailable'}) // 503 ``` -------------------------------- ### Mock.heredoc() Usage Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Use Mock.heredoc to extract multiline strings from function comments. This is useful for defining HTML templates or multiline data within your code. ```javascript Mock.heredoc(function() { /* content */ }) ``` ```javascript var html = Mock.heredoc(function() { /*!
@NAME @EMAIL
*/ }) ``` -------------------------------- ### Mock.mock() Signatures Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Illustrates the different ways Mock.mock() can be called, covering data generation and AJAX request interception with various parameter combinations. ```javascript Mock.mock(template) Mock.mock(rurl, template) Mock.mock(rurl, rtype, template) Mock.mock(rurl, rtype, function(options)) Mock.mock(rurl, function(options)) ``` -------------------------------- ### URL Matching for Mocking Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Define mock responses based on URL patterns. Mock.js supports exact string matching, regular expression patterns, and full URL matching. ```javascript Mock.mock('/api/users', ...) // Exact string Mock.mock(/\/api\/users/, ...) // Regex pattern Mock.mock('http://example.com/...', ...) // Full URL ``` -------------------------------- ### Number Generation Rules in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/types.md Illustrates rules for generating numbers. Covers random integers within a range, fixed increments, and generating a specific quantity of random integers. ```javascript // Random integer 0-100 'count|0-100': 1 // Fixed increment by 2 'id|+2': 1 // Generate 5-10 random integers 'random|5-10': 0 ``` -------------------------------- ### Number Data Type Example Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Numbers can be used directly or generated within a specified range. Use rules like `|18-65` to define a numeric range for generation. ```javascript 1 // Use or generate |18-65 ``` -------------------------------- ### Mocking Raw Text Body Requests Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Intercepts POST requests to '/api/data' and accesses the raw text body. Includes an example of sending raw text data. ```javascript Mock.mock('POST', '/api/data', function(options) { var text = options.body // Raw string return {code: 0} }) ``` ```javascript // Sender xhr.send('raw text data') ``` -------------------------------- ### XHR Request Flow with Event Listeners Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Demonstrates the lifecycle of an XMLHttpRequest, including 'loadstart', 'progress', and 'load' events, as intercepted by Mock.js. ```javascript var xhr = new XMLHttpRequest() xhr.addEventListener('loadstart', function() { console.log('Request starting') }) xhr.open('GET', '/api/users') // At this point, Mock checks if URL is registered xhr.addEventListener('progress', function(e) { console.log('Loading:', e.loaded, e.total) }) xhr.send() // Response is returned after mock timeout delay xhr.addEventListener('load', function() { console.log('Complete:', xhr.responseText) }) ``` -------------------------------- ### Mocking Form Data Requests Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Intercepts POST requests to '/api/users' and logs the form data body. Includes an example of sending form data using XMLHttpRequest. ```javascript Mock.mock('POST', '/api/users', function(options) { // options.body contains form data string console.log(options.body) return {code: 0, message: 'OK'} }) ``` ```javascript // Sender var xhr = new XMLHttpRequest() xhr.open('POST', '/api/users') var formData = new FormData() formData.append('name', 'John') formData.append('email', 'john@example.com') xhr.send(formData) ``` -------------------------------- ### Configure Global Mock Settings Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Configure global options for Mock.js, such as request timeout. Refer to the documentation for all available settings. ```javascript Mock.setup({timeout: '100-500'}) ``` -------------------------------- ### Mocking Response Headers with Metadata in Body Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Illustrates how to include metadata, such as 'X-Total-Count' and 'X-Page-Size', in the response body when custom response headers are not directly supported. ```javascript Mock.mock('/api/users', { 'code': 0, 'headers': { 'X-Total-Count': 100, 'X-Page-Size': 10 }, 'data': [] }) ``` -------------------------------- ### Mock.js Project File Structure Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/README.md This is the directory structure for the Mock.js project. It helps in understanding the organization of different modules and documentation files. ```tree /workspace/home/output/ ├── README.md ← You are here ├── INDEX.md ← Master index & overview ├── quick-start.md ← Essential patterns ├── api-reference-mock.md ← Main Mock API ├── api-reference-random.md ← Random methods (100+) ├── handler.md ← Internal processing ├── utilities.md ← Helper functions ├── types.md ← Data types & schemas ├── configuration.md ← Setup options ├── template-syntax.md ← Template rules └── xhr-interception.md ← AJAX mocking ``` -------------------------------- ### Mock.js Timeout Configuration Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/INDEX.md Configure the timeout setting in Mock.setup() to control response delays. Set timeout to 0 for faster tests or a range (e.g., '100-500') to simulate realistic network latency. ```javascript Mock.setup({timeout: 0}) // No delay, tests run faster ``` ```javascript Mock.setup({timeout: '100-500'}) // Simulates network ``` -------------------------------- ### Mock AJAX API Endpoint Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/README.md Intercept and mock XMLHttpRequest and Fetch API calls to a specific endpoint. This example mocks the '/api/users' endpoint to return a list of users. ```javascript Mock.mock('/api/users', { 'data|5': [{ id|+1: 1, name: '@NAME' }] }) ``` -------------------------------- ### Convert String Template to JSON Schema Source: https://github.com/nuysoft/mock/wiki/Mock.toJSONSchema() Use Mock.toJSONSchema to convert a simple string-based template into its JSON Schema representation. This example shows a template with a repeated character. ```javascript var template = { 'key|1-10': '★' } Mock.toJSONSchema(template) // => { "name": undefined, "path": [ "ROOT" ], "type": "object", "template": { "key|1-10": "★" }, "rule": {}, "properties": [{ "name": "key", "path": [ "ROOT", "key" ], "type": "string", "template": "★", "rule": { "parameters": ["key|1-10", "key", null, "1-10", null], "range": ["1-10", "1", "10"], "min": 1, "max": 10, "count": 3, "decimal": undefined, "dmin": undefined, "dmax": undefined, "dcount": undefined } }] } ``` -------------------------------- ### Relative Path References in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Reference data from the current level or parent levels using relative paths starting with '/'. This is useful for creating nested data structures. ```javascript Mock.mock({ 'firstName': 'John', 'lastName': 'Doe', 'profile': { 'name': '@/firstName @/lastName' } }) // Result: profile.name = 'John Doe' ``` -------------------------------- ### Absolute Path References in Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/quick-start.md Reference data from the root of the mock object using an absolute path starting with '/'. Ensure the referenced key exists at the root level. ```javascript Mock.mock({ 'id': 123, 'user': { 'userId': '@/id' // References root id } }) // Result: user.userId = 123 ``` -------------------------------- ### Pass-Through Requests with Mock.js Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Illustrates how Mock.js allows non-mocked URLs to pass through and make real network requests. Use this to test both mocked and actual API endpoints. ```javascript // Mock this URL Mock.mock('/api/mocked', {code: 0, data: []}) // Don't mock - uses real network var xhr = new XMLHttpRequest() xhr.open('GET', '/api/real') // Not intercepted xhr.send() // Makes real HTTP request ``` -------------------------------- ### Intercept with Custom Function Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/api-reference-mock.md Intercepts requests matching a regex pattern ('/api/search') with a GET method using a custom function. The function receives options and returns the mock data. ```javascript Mock.mock( /\/api\/search/, 'GET', function(options) { return { code: 0, data: [{ id: Mock.Random.id(), text: Mock.Random.sentence() }] } }) ``` -------------------------------- ### Register Mocked URL with Template Source: https://github.com/nuysoft/mock/blob/refactoring/_autodocs/xhr-interception.md Use `Mock.mock()` to register a URL and its corresponding template for mocked responses. Supports exact URLs, regex, and wildcard patterns. ```javascript Mock.mock(url, template) ``` ```javascript Mock.mock(method, url, template) ``` ```javascript Mock.mock(url, method, template) ```