{"id":19977497,"url":"https://github.com/lsycxyj/gulp-mocker","last_synced_at":"2026-05-13T09:36:40.984Z","repository":{"id":57258280,"uuid":"132164887","full_name":"lsycxyj/gulp-mocker","owner":"lsycxyj","description":"A mock server for gulp and beyond gulp. Enjoy mocking!","archived":false,"fork":false,"pushed_at":"2019-05-04T03:30:44.000Z","size":554,"stargazers_count":2,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-13T01:49:38.374Z","etag":null,"topics":["gulp","gulp-plugin","mock","mocking"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"lgpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lsycxyj.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-05-04T16:38:04.000Z","updated_at":"2019-05-04T03:30:46.000Z","dependencies_parsed_at":"2022-08-25T21:23:47.451Z","dependency_job_id":null,"html_url":"https://github.com/lsycxyj/gulp-mocker","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsycxyj%2Fgulp-mocker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsycxyj%2Fgulp-mocker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsycxyj%2Fgulp-mocker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lsycxyj%2Fgulp-mocker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lsycxyj","download_url":"https://codeload.github.com/lsycxyj/gulp-mocker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241411542,"owners_count":19958753,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["gulp","gulp-plugin","mock","mocking"],"created_at":"2024-11-13T03:28:17.686Z","updated_at":"2026-05-13T09:36:40.932Z","avatar_url":"https://github.com/lsycxyj.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gulp-mocker\n\n\u003e Gulp Mocker. A mock server can be used with gulp, or run it in command line, or run it programmatically, and more. Enjoy mocking!\n\n### Pull requests are welcome :)\n\n![Build Status](https://travis-ci.org/lsycxyj/gulp-mocker.svg?branch=master)\n[![Coverage](https://img.shields.io/codecov/c/github/lsycxyj/gulp-mocker/master.svg)](https://codecov.io/github/lsycxyj/gulp-mocker?branch=master)\n\n## License\nLGPL-V3\n[![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](http://www.gnu.org/licenses/lgpl-3.0)\n\n## Features\n#### Return mock responses just place files into mock directory\n\n\u003e /path/to/api =\u003e 'mock/path/to/api|api.json|api.js'\n\n#### JSONP support\n\n\u003e /path/to/api?callback=jsonp =\u003e jsonp response with 'mock/path/to/api|api.json|api.js' data\n\n#### Highly customized response\n\n\u003e You can write any kind of response in the js response file.\n\n#### Fallback to Proxies\n```javascript\n// option\n{\n    fallback: true,\n    proxies: [{\n        // Proxy option\n    }]\n}\n```\n\n#### HTTPS Support\n```javascript\n// option\n{\n    useHTTPS: true,\n    httpsOptions: {\n        // HTTPS Option\n    }\n}\n```\n\n#### Mock File Relocation\n```javascript\n// option\n{\n    mockPathRewrite({ctx, defaultPath) {\n        let ret = defaultPath;\n        if (defaultPath === '/index.php') {\n            const q = ctx.query;\n            ret = `/${q.class}/${q.method}`;\n        }\n        return ret;\n    }\n}\n```\n\n#### With Gulp\n```javascript\nconst gulpMocker = require('gulp-mocker');\ngulp.src('whatever')\n    .pipe(gulpMocker({\n        // Put options here\n    }))\n    .pipe(// Nothing changed, do whatever you want)\n```\n\n#### Run it with command line\n```sh\n$ npm install -g gulp-mocker\n# Further more, the config file can be ignored!\n$ gulp-mock --config mock.config.js\n```\n`gulp-mock -h` for more information\n\n#### Run it programmatically\n```javascript\nconst mod = require('gulp-mocker/src/server');\nconst { webServer, app } = mod.startServer({\n    // Options\n});\n```\n\n#### Tested (Not 100% though LOL)\n[![Coverage](https://img.shields.io/codecov/c/github/lsycxyj/gulp-mocker/master.svg)](https://codecov.io/github/lsycxyj/gulp-mocker?branch=master)\n\n## Installation\n\n[![gulp-mocker](https://nodei.co/npm/gulp-mocker.png)](https://npmjs.org/package/gulp-mocker)\n\n`npm install gulp-mocker`\n\n## Examples\n\u003e See \"mock\" folder\n\n## Options\n```javascript\nconst DEFAULT_OPTS = {\n    // {Boolean}: Whether add Allow-Cross-Origin header in response\n    allowCrossOrigin: false,\n    // {Array\u003cString\u003e|String}: Access-Control-Allow-Headers value\n    allowCrossOriginHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept'],\n    // {String}: Access-Control-Allow-Host value\n    allowCrossOriginHost: '*',\n    // {Array\u003cString\u003e|String}: Access-Control-Allow-Methods\n    allowCrossOriginMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n    // {Object}: Config object for koa-bodyparser\n    bodyParserConfig: {\n        jsonLimit: '100mb',\n        formLimit: '100mb',\n    },\n    // {Object}: Config object for koa-busboy\n    busboyConfig: {},\n    /*\n     *  {Boolean|String}: Whether use fallback. Available values:\n     *      false: Not use fallback\n     *      true|'proxy': Use fallback if the mock server fail to return response and fallback to proxy\n     */\n    fallback: false,\n    /*\n     *  {Array\u003cString|Function\u003e}: What kinds of circumstances are considered as failure.\n     *  Available embedded rules:\n     *      'emptyBody': If ctx.body is empty\n     *      'status404': If the status code is 404\n     *      'status500': If the status code is 500\n     *  If it's a function, the signature should be like this:\n     *      function: boolean ({\n     *         // `ctx` of koa.\n     *         ctx: Object,\n     *      })\n     */\n    fallbackRules: ['emptyBody', 'status404', 'status500'],\n    // {String}: Mock server host name\n    host: 'localhost',\n    // {Boolean}: Whether use https\n    httpsEnabled: false,\n    // {Object}: https options for `https.createServer()`\n    httpsOptions: {\n        key: fs.readFileSync(path.resolve(__dirname, '../ssl/ssl.key')),\n        cert: fs.readFileSync(path.resolve(__dirname, '../ssl/ssl.crt')),\n    },\n    // {String}: Param name of JSONP\n    jsonpParamName: 'callback',\n    /*\n     *  {String}: Logging level. Available values: 'none', 'error', 'warn', 'info'\n     *  The levels above are in order. Any levels after the specific level of logging will be ignored.\n     */\n    logLevel: LEVEL_INFO,\n    // {Array\u003cFunction\u003e|Function}: Additional koa middlewares\n    middlewares: [],\n    // {String}: Mock config file name\n    mockConfigName: '_.config.js',\n    // {Array\u003cString\u003e}: Mock response will try to find files by the following order\n    mockExtOrder: ['', '.json', '.js'],\n    // {String}: Mock responses files' root path\n    mockPath: './mock',\n    /*\n     *  {Function}: Rewrite the request path to the specified one. By default it won't rewrite.\n     *  Note that this option won't affect the url of fallback request\n     *  The function has following signature:\n     *      function: String ({\n     *         // `ctx` of koa.\n     *         ctx: Object,\n     *         // The request path of default behaviour\n     *         defaultPath: String,\n     *      })\n     */\n    mockPathRewrite: null,\n    // {Function}: Listener function when the web server starts\n    onServerStart: null,\n    // {Number}: Port of server\n    port: 10086,\n    /*\n     *  {Array\u003c{\n     *      // Matching rule whether to use proxy or not, which can be parsed by path-to-regexp if it's a string. Required.\n     *      source: RegExp|String,\n     *      // `context` param of http-proxy-middleware. Optional.\n     *      context?: String,\n     *      // `options` param of http-proxy-middleware. Optional.\n     *      options?: Object\n     *  }\u003e}: Proxy settings for http-proxy-middleware\n     */\n    proxies: [],\n    /*\n     *  {Boolean}: The mock server will scan all mock config files and cache them when the server starts.\n     *  It will try to recollect the config files if any of config files changes when it's set to `true`\n     */\n    watchMockConfig: true,\n    /*\n     *  {Array\u003c{\n     *      // Matching rule whether to rewrite the request, which can be parsed by path-to-regexp if it's a string\n     *      // Note that this option will affect the url of fallback request\n     *      from: RegExp|String,\n     *      // Where the request should be rewritten to:\n     *      //      If it's a string, the request path will be replaced by it.\n     *      //      If it's a function, the request path will be replaced by the return result of it. The signature should be like this:\n     *      //          function: string (result: {\n     *      //              // `ctx` of koa.\n     *      //              ctx: Object,\n     *      //              // `exec` result of RegExp object .\n     *      //              exec: Array,\n     *      //              // Keys from path-to-regexp. Available when `from` is a string.\n     *      //              keys: Array,\n     *      //          })\n     *      to: String|Function\n     *  }\u003e}\n     */\n    rewrites: [],\n};\n```\n\n## Mock Config File\n```javascript\n// Note: All the options will be merged shallowly\nmodule.exports = {\n    /**\n     * Wrapper\n     * Only works for json response.\n     * Default: null\n     */\n    /**\n     * Static Response Wrapper\n     * If the value of \"wrapper\" is a plain object, it will be a \"Static Response Wrapper\"\n     * All responses will wrap the same format of wrapper,\n     * and the \"Wrapper Content Placeholder\" will replace the response content\n     */\n    // wrapper: {\n    //     code: 200,\n    //     msg: 'success',\n    //     data: '{{!--WrapperContent--}}',\n    // },\n    /**\n     * Dynamic Response Wrapper\n     * If the value of \"wrapper\" is a function, it will be a \"Dynamic Response Wrapper\"\n     * All responses can be handled manually by you. And you should return a JSON object.\n     * @param {Object}\n     *      ctx {Object}: context of koa\n     *      resResult {Object}: mock response content\n     *      helpers: {Object}: See \"Helpers\"\n     * @returns {Object|Promise\u003cObject\u003e}: Dynamic wrapper processed response. The Object should have the following structure\n     *      body {*}: The value will be set as the koa's body of ctx\n     *      contentType? {String}: Optional. The value will be used as content type if it's set.\n     *      status? {Number}: Optional. Response status code.\n     */\n    // wrapper: function({ ctx, resResult }) {\n    //     // Do whatever you want\n    //     return {\n    //         body: ctx.body,\n    //     };\n    // },\n\n    /**\n     * Wrapper Content Placeholder\n     * Default: {{!--WrapperContent--}}\n     *\n     * This string will be replaced by the response data in the wrapper.\n     * Only works for Static Response Wrapper\n     */\n    wrapperContentPlaceHolder: '{{!--WrapperContent--}}',\n\n    /**\n     * Mock Type\n     * Default: 'normal'\n     *\n     * Available values:\n     * normal: It will try to find certain kinds of extensions of file by the request path. See the config's \"mockExtOrder\" property.\n     * mockjs: Responses will be treated as the parameters of MockJS after the process of \"normal\"\n     */\n    mockType: 'normal',\n\n    /**\n     * Delay\n     * Default: 0\n     *\n     * Response delay emulation in millisecond.\n     */\n    delay: 0,\n\n    /**\n     * Pass through Proxy\n     * Default: false\n     *\n     * Any request will pass through the proxy directly. Only available when the fallback is proxy and the proxy is available.\n     */\n    passThroughProxy: false,\n\n    /**\n     * Additional http headers for responses.\n     * eg. {'Etag': '1234'}\n     * Default: Empty object\n     */\n    headers: {},\n};\n```\n\n## Dynamic response\n```javascript\n/**\n* @returns {Object|Promise\u003cObject\u003e}: A response generated by js should return the following structure:\n*      body {*}: The value will be set as the koa's body of ctx\n*      contentType? {String}: Optional. The value will be used as content type if it's set.\n*      headers? {Object}: Optional. Additional http headers for responses. eg. {'Etag': '1234'}\n*                         In addition, headers in dynamic response will override headers in mock config file\n*                         if they have same keys.\n*      passThroughProxy? {Boolean}: Optional. Request will pass through the proxy directly.\n*                                   Only available when the fallback is proxy and the proxy is available.\n*      status? {Number}: Optional. Response status code.\n*/\n```\n\n## Helpers\n```javascript\n/**\n * Helpers\n * It's a group of tools that help you to make dynamic responses. It has the following properties:\n *\n *    // `mime` from npm: https://www.npmjs.com/package/mime\n *    mime,\n *\n *    // `mockjs` from npm: https://www.npmjs.com/package/mockjs\n *    Mock,\n *\n *    // Generate a stream of image\n *    // @param opts: {\n *    //          // Size of image by pixel. Format: `${width}x${height}`\n *    //          size: string,\n *    //          // Background color of image\n *    //          background: string,\n *    //          // Foreground color of text\n *    //          foreground: string,\n *    //          // Format of image. Available values: png, jpg, gif\n *    //          format: string,\n *    //          // Foreground text content\n *    //          text: string,\n *    //      }\n *    // @returns {Promise.\u003cstream\u003e} The stream of image\n *    genImageStream: function,\n *\n *    // Generate a image response\n *    // @param opts {Object}: The same as genImageStream\n *    // @returns {Promise.\u003cObject\u003e} The response for dynamic response\n *    genImageResponse: function,\n *\n *    // Merge query, post body, parameters from request\n *    // @param ctx: `ctx` of koa\n *    // @returns {Object}\n *    mergeParams: function,\n */\n```\n\n## TODO list\n- More test cases.\n- Generate image response by myself instead of depending other online services.\n- More other features.\n\n## Recipes and Case Studies\n### Multiple hosts with fallback and *WebpackDevServer* by only one mocking server\n1. Set the proxy option of *WebpackDevServer* and forward all the requests to the mocking server. Let's say the dev server listens to port 8080 and the mocking server listens port 10086 of localhost:\n```javascript\nconst webpackConfig = {\n    devServer: {\n        disableHostCheck: true,\n        port: 8080,\n        proxy: {\n            '/api': {\n                target: 'http://localhost:10086',\n            },\n        },\n    },\n};\n```\n1. Change your requests to multiple host aliases of localhost. Let's say you have two hosts `a.com` and `b.com` which provide API services.\n    1. Edit host file\n    ```\n    127.0.0.1 localhost.a.com\n    127.0.0.1 localhost.b.com\n    ```\n    1. Change your API hosts from `x.com/api` to `localhost.x.com:10086/api`\n1. And the options for *gulp-mocker* should be like this:\n```javascript\ngulpMocker({\n    mockPath: './mock',\n    port: 10086,\n    fallback: true,\n    proxies: [\n        {\n            source: '/api/(.*)',\n            options: {\n                // Default target\n                target: 'a.com',\n                changeOrigin: true,\n                router: {\n                    // Override default target by different coming hosts\n                    'localhost.a.com:8080': 'http://a.com',\n                    'localhost.b.com:8080': 'http://b.com',\n                },\n            },\n        },\n    ],\n    /*\n    mockPathRewrite({ ctx, defaultPath }) {\n        // Change the local mocking file path if it's needed.\n        return 'newPath';\n    }\n    */\n});\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flsycxyj%2Fgulp-mocker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flsycxyj%2Fgulp-mocker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flsycxyj%2Fgulp-mocker/lists"}