{"id":13399116,"url":"https://github.com/jakerella/jquery-mockjax","last_synced_at":"2026-02-25T00:17:31.879Z","repository":{"id":57282237,"uuid":"647892","full_name":"jakerella/jquery-mockjax","owner":"jakerella","description":"The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses","archived":false,"fork":false,"pushed_at":"2024-09-09T22:53:32.000Z","size":2252,"stargazers_count":2104,"open_issues_count":7,"forks_count":370,"subscribers_count":83,"default_branch":"master","last_synced_at":"2025-11-22T22:03:19.216Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jakerella.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2010-05-05T06:18:23.000Z","updated_at":"2025-10-11T13:51:04.000Z","dependencies_parsed_at":"2024-05-04T05:34:06.496Z","dependency_job_id":"94ee5377-8c11-4313-a8e1-9936906b1c86","html_url":"https://github.com/jakerella/jquery-mockjax","commit_stats":{"total_commits":518,"total_committers":79,"mean_commits":6.556962025316456,"dds":0.5772200772200773,"last_synced_commit":"2a143bc79bb075c81aa748361a4a7fe91af0f4ad"},"previous_names":["appendto/jquery-mockjax"],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/jakerella/jquery-mockjax","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jakerella%2Fjquery-mockjax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jakerella%2Fjquery-mockjax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jakerella%2Fjquery-mockjax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jakerella%2Fjquery-mockjax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jakerella","download_url":"https://codeload.github.com/jakerella/jquery-mockjax/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jakerella%2Fjquery-mockjax/sbom","scorecard":{"id":203463,"data":{"date":"2025-08-11","repo":{"name":"github.com/jakerella/jquery-mockjax","commit":"204eb93796e721f6d248996bf0dd6e415b030384"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":4.5,"checks":[{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Maintained","score":2,"reason":"0 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 2","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Code-Review","score":2,"reason":"Found 2/8 approved changesets -- score normalized to 2","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Security-Policy","score":4,"reason":"security policy file detected","details":["Info: security policy file detected: .github/SECURITY.md:1","Warn: no linked content found","Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/SECURITY.md:1","Info: Found text in security policy: .github/SECURITY.md:1"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 29 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-16T23:13:51.199Z","repository_id":57282237,"created_at":"2025-08-16T23:13:51.199Z","updated_at":"2025-08-16T23:13:51.199Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27487175,"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","status":"online","status_checked_at":"2025-12-03T02:00:06.367Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2024-07-30T19:00:34.322Z","updated_at":"2026-02-25T00:17:31.867Z","avatar_url":"https://github.com/jakerella.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","前端 - broswer端","Testing"],"sub_categories":["数据","Miscellaneous Plugins"],"readme":"# jQuery Mockjax: Ajax request mocking #\n\nThere are some minor breaking changes in v2, so if you need an older version, please check the [v1.x](https://github.com/jakerella/jquery-mockjax/tree/v1.x) branch or the list of [releases](https://github.com/jakerella/jquery-mockjax/tags) in Github.\n\njQuery Mockjax provides request/response mocking for ajax requests using the jQuery API and provides all standard behaviors in the request/response flow.\n\nYou may report any issues you may find [in the github issue tracking](https://github.com/jakerella/jquery-mockjax/issues).\n\n**Table of Contents**\n\n* [About Mockjax and Its History](#about-mockjax-and-its-history)\n* [Basic Documentation](#basic-documentation)\n  * [API Methods](#api-methods)\n  * [Overview: Your First Mock](#overview-your-first-mock)\n  * [Mockjax in Depth](#mockjax-in-depth)\n* [Detailed Request and Response Definition](#detailed-request-and-response-definition)\n  * [Defining a Request to Match](#defining-a-request-to-match)\n  * [Defining Multiple Requests](#defining-multiple-requests)\n  * [Defining a Response](#defining-a-response)\n* [Advanced Mocking Techniques](#advanced-mocking-techniques)\n  * [Simulating Response Time and Latency](#simulating-response-time-and-latency)\n  * [Simulating HTTP Response Statuses](#simulating-http-response-statuses)\n  * [Setting the Content-Type](#setting-the-content-type)\n  * [Setting Additional HTTP Response Headers](#setting-additional-http-response-headers)\n  * [Dynamically Generating Mock Definitions](#dynamically-generating-mock-definitions)\n  * [Accessing Request Headers](#accessing-request-headers)\n  * [Forced Simulation of Server Timeouts](#forced-simulation-of-server-timeouts)\n  * [Dynamically Generating Mock Responses](#dynamically-generating-mock-responses)\n  * [Data Types](#data-types)\n  * [Performing Actions After Request Completion](#performing-actions-after-request-completion)\n  * [Globally Defining Mockjax Settings](#globally-defining-mockjax-settings)\n  * [Setting a Global URL Namespace](#setting-global-url-namespace)\n  * [Removing Mockjax Handlers](#removing-mockjax-handlers)\n* [Miscellaneous Information](#miscellaneous-information)\n  * [jQuery Version Support](#jquery-version-support)\n  * [Browsers Tested](#browsers-tested)\n  * [Using Mockjax in Other Ways (Node, browserify, etc)](#using-mockjax-in-other-ways)\n  * [Logging](#logging)\n  * [Release History](#release-history)\n  * [License](#license)\n\n\n## About Mockjax and Its History ##\n\nMost backend developers are familiar with the concepts of [mocking\nobjects](http://en.wikipedia.org/wiki/Mock_object) or stubbing in\nmethods for unit testing. For those not familiar with mocking, it's the\nsimulation of an interface or API for testing or integration development\npurposes. Mocking with front-end development though is still quite new. Mockjax\ngives front end developers the ability to define ajax requests that should be\nmocked out, as well as how those requests should be responded to. These mocks\ncan be extremely simple or quite complex, representing the entire request-response\nworkflow.\n\nThis plugin was originally developed by appendTo in March 2010. That company\nclosed in 2014 and the project was taken over by a former employee, \n[@jakerella](https://jordankasper.com).\n\n\n## Basic Documentation ##\n\n### API Methods ###\n\nMockjax consists of just a few methods, each listed below. You'll find plenty of\nexamples in the sections below, but if you're looking for a specific option,\ncheckout this list:\n\n* `Number $.mockjax(/* Object */ options)`\n  * Sets up a mockjax handler for a matching request\n  * Returns that handler's index, can be used to clear individual handlers\n  * `options`: [Object] Defines the settings to use for the mocked request\n      * `url`: [String | RegExp] Specifies the url of the request that the data should be mocked for. If it is a string and contains any asterisks ( `*` ), they will be treated as a wildcard by translating to a regular expression. Any `*` will be replaced with `.+`. If you run into trouble with this shortcut, switch to using a full regular expression instead of a string and asterisk combination\n      * `data`: [Object | Function] In addition to the URL, match parameters\n      * `type`: [String] Specify what HTTP method to match, usually GET or POST. Case-insensitive, so `get` and `post` also work\n      * `headers`: [Object] Keys will be simulated as additional headers returned from the server for the request (**NOTE: This is NOT used to match request headers!**)\n      * `status`: [Number] An integer that specifies a valid server response code. This simulates a server response code\n      * `statusText`: [String] Specifies a valid server response code description. This simulates a server response code description\n      * `responseTime`: [Number] An integer that specifies a simulated network\n         and server latency (in milliseconds). Default is `500`. Setting this\n\t to `0` will minimize the simulated latency\n      * `isTimeout`: [Boolean] Determines whether or not the mock will force a timeout on the request\n      * `contentType`: [String] Specifies the content type for the response\n      * `response`: [Function] A function that accepts the request settings and allows for the dynamic setting of response settings (including the body of the response) upon each request (see examples below)\n      * `responseText`: [String] Specifies the mocked text, or a mocked object literal, for the request\n      * `responseXML`: [String] Specifies the mocked XML for the request\n      * `proxy`: [String] Specifies a path to a file, from which the contents will be returned for the request\n      * `lastModified`: [String] A date string specifying the mocked last-modified time for the request. This is used by `$.ajax` to determine if the requested data is new since the last request\n      * `etag`: [String] Specifies a unique identifier referencing a specific version of the requested data. This is used by `$.ajax` to determine if the requested data is new since the last request. (see [HTTP_ETag](http://en.wikipedia.org/wiki/HTTP_ETag))\n      * `onAfterSuccess`: [Function] A callback that will be called after the success method has been called, this is useful to check a condition after the call has been completed\n      * `onAfterError`: [Function] A callback that will be called after the error method has been called, this is useful to check a condition after the call has been completed\n      * `onAfterComplete`: [Function] Similar to onAfterSuccess, but will be executed after the complete method has been called\n* `Object $.mockjax.handler(/* Number */ id)`\n  * Returns the mock request settings for the handler with the provided `id`. Be careful here, you're accessing the inner workings of the plugin, any changes to this object could be bad.\n* `Array $.mockjax.handlers()`\n  * Returns the array of mock handlers. **NOTE:** This array is NOT modified when a handler is cleared, the cleared handler position is simply set to `null`. As such, the array length will only change when new mocks are added. Be careful here, you're accessing the inner workings of the plugin, any changes to the array could be very bad.\n* `void $.mockjax.clear([/* Number || String */ identifier])`\n  * If the `identifier` provided is a Number, the handler with that ID is cleared (that is, requests matching it will no longer do so, the handler is completely removed)\n  * If the `identifier` provided is a String, the handler with that matching URL is cleared.\n  * If no `identifier` is provided, *ALL handlers are cleared*, resetting Mockjax to its initial state\n* `Array\u003cObject\u003e $.mockjax.mockedAjaxCalls()`\n  * Returns an array of all mocked ajax calls with each entry being the request settings object as passed into the `$.mockjax()` function\n  * If `$.mockjaxSettings.retainAjaxCalls is set to false, this will always be empty\n* `Array\u003cObject\u003e $.mockjax.unfiredHandlers()`\n  * Returns an array of all mock handler settings that have not been used. In other words, if a handler has been used for a `$.ajax()` call then it will _not_ appear in this array\n* `Array\u003cObject\u003e $.mockjax.unmockedAjaxCalls()`\n  * Returns an array of all unmocked Ajax calls that were made. The array contains the settings object passed into `$.ajax({...})`\n  * If `$.mockjaxSettings.retainAjaxCalls is set to false, this will always be empty\n* `void $.mockjax.clearRetainedAjaxCalls()`\n  * Empties the arrays returned by `$.mockjax.mockedAjaxCalls` and `$.mockjax.unmockedAjaxCalls`\n\n### Overview: Your First Mock ###\n\nOur first example will be for a simple REST service for a fortune app\nwith the REST endpoint being `/restful/fortune` which returns the\nfollowing JSON message:\n\n```json\n{\n    \"status\": \"success\",\n    \"fortune\" : \"Are you a turtle?\"\n}\n```\n\nTo pull the fortune into our page, we'd use the following HTML and jQuery\ncode:\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003ctitle\u003eFortune App\u003c/title\u003e\n    \u003cscript src=\"http://code.jquery.com/jquery-1.11.1.min.js\"\u003e\u003c/script\u003e\n  \u003c/head\u003e\n\u003cbody\u003e\n  \u003cdiv id=\"fortune\"\u003e\u003c/div\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n```javascript\n$.getJSON(\"/restful/fortune\", function(response) {\n  if ( response.status == \"success\") {\n    $(\"#fortune\").html( \"Your fortune is: \" + response.fortune );\n  } else {\n    $(\"#fortune\").html( \"Things do not look good, no fortune was told\" );\n  }\n});\n```\n\nAt this point if we were to run this code it would fail since the REST\nservice has yet to be implemented. This is where the benefit of the\nMockjax plugin starts to pay off. The first step in using Mockjax is to\ninclude the plugin by just adding a regular script tag:\n\n```html\n\u003chead\u003e\n  ...\n  \u003cscript src=\"vendor/jquery.mockjax.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n```\n\nOnce you have that included, you can start intercepting Ajax requests\nand mocking the responses. So let's mock out the service by including\nthe following code:\n\n```javascript\n$.mockjax({\n  url: \"/restful/fortune\",\n  responseText: {\n    status: \"success\",\n    fortune: \"Are you a mock turtle?\"\n  }\n});\n```\n\n**Defining a JSON string inline requires a `JSON.stringify()` method to be\navailable. For some browsers you may need to include\n[json2.js](https://raw.github.com/douglascrockford/JSON-js/master/json2.js),\nwhich is included in the `lib` folder.** However, you could also simply\nprovide an already stringified version of your JSON in the `responseText`\nproperty.\n\n_If you plan on mocking xml responses, you may also have to include\n`jquery.xmldom.js`, which can also be found in the `lib` folder._\n\n### Mockjax in Depth ###\n\nWhat Mockjax does at this point is replace the `$.ajax()` method with a\nwrapper that transparently checks the URL being requested. If the URL\nmatches one defined by `$.mockjax()`, it intercepts the request\nand sets up a mock `XMLHttpRequest` object before executing the\n`jQuery.ajax()` handler. Otherwise, the request is handed back to the\nnative `$.ajax()` method for normal execution. One benefit in this\nimplementation detail is that by simulating the `XMLHttpRequest` object,\nthe plugin continues to make use of jQuery's native ajax handling, so\nthere are no concerns with implementing a custom Ajax workflow.\n\nAs you write code to mock responses, there's great value in the fact that\nthere are no modifications required to production code. The mocks can be\ntransparently inserted. This provides easy integration into most\nframeworks by including the plugin and mock definitions through your\nbuild framework. It's also possible to include it at run time by\nlistening for a query string flag and injecting the plugin and definitions.\n\nNow let's look at the various approaches to defining mocks as offered by\nthe plugin. The sections below feature an extensive overview of the\nflexibility in Mockjax and creating responses.\n\n#### Data Types Available for Mocking ####\n\njQuery is able to handle and parse `Text`, `HTML`, `JSON`, `JSONP`,\n`Script` and `XML` data formats and Mockjax is able to mock any of those\nformats. Two things to note: depending upon how you mock out `JSON` and\n`JSONP` you may need to include [json2.js](https://raw.github.com/douglascrockford/JSON-js/master/json2.js)\nfor the `JSON.stringify()` method (older browsers only, typically). Additionally\nif you mock XML inline, you'll need to include the [`xmlDOM`](http://github.com/jakerella/jquery-xmldom)\nplugin that transforms a string of XML into a DOM object. However, if you use\nthe proxy approach outlined below then there should be no need to include either\nthe JSON or XMLDOM plugins in any case.\n\n\n## Detailed Request and Response Definition ##\n\n### Defining a Request to Match ###\n\nThe first thing you need to do when mocking a request is define the URL\nend-point to intercept and mock. As with our example above this can be a\nsimple string:\n\n```javascript\n$.mockjax({\n  url: \"/url/to/rest-service\"\n});\n```\n\nor contain a `*` as a wildcard:\n\n```javascript\n$.mockjax({\n  // Matches /data/quote, /data/tweet etc.\n  url: \"/data/*\"\n});\n```\n\nor a full regular expression:\n\n```javascript\n$.mockjax({\n  // Matches /data/quote, /data/tweet but not /data/quotes\n  url: /^\\/data\\/(quote|tweet)$/i\n});\n```\n\nYou can also match against the data option in addition to url:\n\n```javascript\n$.mockjax({\n  url:  \"/rest\",\n  data: { action: \"foo\" }\n});\n```\n\nThe data option may be a custom matching function returning `true` of `false`\nwhether the data is expected or not:\n\n```javascript\n$.mockjax({\n  url: \"/rest\",\n  data: function( data ) {\n    return deepEqual( data, expected );\n  }\n});\n```\n\nThe data function is a recommended place for assertions. Return `true` and let\na testing framework of choice do the rest:\n\n```javascript\n$.mockjax({\n  url: \"/rest\",\n  data: function ( json ) {\n    assert.deepEqual( JSON.parse(json), expected ); // QUnit example.\n    return true;\n  }\n});\n```\n\nTo capture URL parameters, use a capturing regular expression for the\nURL and a `urlParams` array to indicate, ordinally, the names of the\nparamters that will be captured:\n\n```javascript\n$.mockjax({\n  // matches /author/{any number here}/isbn/{any number with dashes here}\n  // for example: \"/author/1234/isbn/1234-5678-9012-0\"\n  url: /^\\/author\\/([\\d]+)\\/isbn\\/([\\d\\-]+)$/,\n  // names of matching params\n  urlParams: [\"authorID\", \"isbnNumber\"],\n  response: function (settings) {\n    var authorID = settings.urlParams.authorID;\n    var isbnNumber = settings.urlParams.isbnNumber;\n    // etc...\n  }\n});\n```\n\n### Defining Multiple Requests ###\n\nSince version 2.2 it is allowed to define several requests at once.\n`$.mockjax([...])` returns a array of handlers' indexes. It is possible to\nreset handler by index. Read more in [Removing Mockjax Handlers](#removing-mockjax-handlers).\n\n```javascript\nvar handlers = $.mockjax([\n  {url: '/rest', responseText: 'one'},\n  {url: '/rest', responseText: 'two'}\n]);\n\n$.mockjax.clear(handlers[0]);\n```\n\n### Defining a Response ###\n\nThe second step is to define the type and content of the response. The two main\nproperties you will be dealing with are either `responseText` or\n`responseXML`. These properties mirror the native `XMLHttpRequest`\nobject properties that are set during a live response. There are three\ndifferent patterns for specifying the responses: Inline, Proxy, and\nCallback.\n\n#### Inline Responses ####\n\nA simple text response would be:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  responseText: \"A text response from the server\"\n});\n```\n\nA simple JSON response would be:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  // You may need to include the [json2.js](https://raw.github.com/douglascrockford/JSON-js/master/json2.js) library for older browsers\n  responseText: { \"foo\": \"bar\" }\n});\n```\n\nAlso note that a JSON response is really just a text response that jQuery will\nparse as JSON for you (and return a JSON object to the `success` and `complete`\ncallbacks).\n\nA simple XML response would be:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  // Need to include the xmlDOM plugin to have this translated into a DOM object\n  responseXML: \"\u003cdocument\u003e\u003cquote\u003eHello world!\u003c/quote\u003e\u003c/document\u003e\"\n});\n```\n\nAs you can see, if you have a significant amount of data being\nmocked this becomes unwieldy. So that brings us to the next pattern:\nthe proxy.\n\n#### Proxy ####\n\nIn this example below, the Mockjax plugin will intercept requests for\n`/restful/api` and redirect them to `/mocks/data.json`:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  proxy: \"/mocks/data.json\"\n});\n```\n\nThe `/mocks/data.json` file can have any valid JSON content you want, and allows\nyou to maintain that mock data in its own file for maintainability.\n\n\u003e Note: If you're testing your code with a poxy, it is best to run an actual web\nserver for the tests. Simply loading `test/index.html` from the file system may\nresult in the proxy file not being loaded correctly. We recommend using something\nlike the [`http-server` npm module](https://www.npmjs.com/package/http-server).\n\n#### Callback ####\n\nIn the final response pattern, we can define a callback function on the\n`response` property and have it set `responseText` or `responseXML` as\nneeded:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  response: function(settings) {\n    // Investigate the `settings` to determine the response...\n\n    this.responseText = \"Hello world!\";\n  }\n});\n```\n\nThe default version of this callback is synchronous. If you provide both parameters\nto the callback function, you can use asynchronous code to set the dynamic response.\n\n```javascript\n$.mockjax({\n  url: '/restful/api',\n  response: function(settings, done) {\n    var self = this;\n    someAsyncMethod(function(data){\n      self.responseText = data;\n      done();\n    });\n  }\n});\n```\n\nNote that the callback is given the settings provided to the `$.mockjax({...})`\nmethod merged with any Ajax settings defined by jQuery or your application. This\nallows you to thoroughly investigate the request before setting the response\nbody (or headers).\n\n\n## Advanced Mocking Techniques ##\n\nAt this point we've looked at a series of basic mocking techniques with\nMockjax and will now unpack some of the additional functionality\ncontained in the plugin.\n\n### Simulating Response Time and Latency ###\n\nSimulating network and server latency for a mock is as simple as adding\na `responseTime` property to your mock definition:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  // Simulate a network latency of 750ms\n  responseTime: 750,\n  responseText: \"A text response from the server\"\n});\n```\n\nYou can also use an interval for `responseTime` to randomize latency:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  // Use a random value between 250ms and 750ms\n  responseTime: [250, 750],\n  responseText: \"A text response from the server\"\n});\n```\n\n### Simulating HTTP Response Statuses ###\n\nIt's also possible to simulate response statuses other than 200 (default\nfor Mockjax) by simply adding a `status` property.\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  // Server 500 error occurred\n  status: 500,\n  responseText: \"A text response from the server\"\n});\n```\n\nThe ability to provide an array of possible response statuses (from which the response\nfor a given request will be randomly picked from):\n\n```javascript\n// Randomly fail\n$.mockjax({\n  url: \"/restful/api\",\n  status: [200,400,500]\n});\n\n// Randomly fail (with a preference towards success)\n$.mockjax({\n  url: \"/restful/api\",\n  status: [200,400,200,500,200]\n});\n```\n\nThese forced error status codes will be handled just as if the server had\nreturned the error: the `error` callback will get executed with the proper\narguments.\n\n### Setting the Content-Type ###\n\nYou can set the content type to associate with the mock response, in the\nexample below, we're setting a JSON content type.\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  contentType: \"application/json\",\n  responseText: {\n    hello: \"World!\"\n  }\n});\n```\n\n### Setting Additional HTTP Response Headers ###\n\nAdditional HTTP Response Headers may be provided by setting a key in the\nheaders object literal:\n\n```javascript\n$.mockjax({\n  url: \"/restful/api\",\n  contentType: \"application/json\",\n  responseText: {\n    hello: \"World!\"\n  },\n  headers: {\n    etag: \"xyz123\"\n  }\n});\n```\n\n### Dynamically Generating Mock Definitions ###\n\nIn some situations, all of your REST calls are based upon a URL schema.\nMockjax has the ability for you to specify a callback function that is\nhanded the `$.ajax` request settings. The callback function may then\neither return false to allow the request to be handled natively, or\nreturn an object literal with relevant Mockjax parameters set. Below is\nan example that rewrites all Ajax requests to proxy to static mocks:\n\n```javascript\n$.mockjax(function(settings) {\n\n  // settings.url might be: \"/restful/\u003cservice\u003e\" such as \"/restful/user\"\n\n  var service = settings.url.match(/\\/restful\\/(.*)$/);\n  if ( service ) {\n    return {\n      proxy: \"/mocks/\" + service[1] + \".json\"\n    };\n  }\n  // If you get here, there was no url match\n  return;\n});\n```\n\n### Accessing Request Headers ###\n\nIn some situations, you may need access to the  request headers to determine\nmatching or response bodies. To do this, you will need to specify a\ncallback function that is handed the `$.ajax` request settings:\n\n```javascript\n$.mockjax(function( requestSettings ) {\n  // Here is our manual URL matching...\n  if ( requestSettings.url === \"/restful/user\" ) {\n    // We have a match, so we return a response callback...\n    return {\n      response: function( origSettings ) {\n\n      \t// now we check the request headers, which may be set directly\n      \t// on the xhr object through an ajaxSetup() call or otherwise:\n\n      \tif ( requestSettings.headers[\"Authentication\"] === \"some-token\" ) {\n      \t  this.responseText = { user: { id: 13 } };\n      \t} else {\n  \t\t  this.status = 403;\n  \t\t  this.responseText = \"You are not authorized\";\n        }\n      }\n    };\n  }\n  // If you get here, there was no url match\n  return;\n});\n```\n\n### Forced Simulation of Server Timeouts ###\n\nBecause of the way Mockjax was implemented, it takes advantage of\njQuery's internal timeout handling for requests. But if you'd like to\nforce a timeout for a request you can do so by setting the `isTimeout`\nproperty to true:\n\n```javascript\n$.mockjax({\n  url: '/restful/api',\n  responseTime: 1000,\n  isTimeout: true\n});\n```\n\n### Dynamically Generating Mock Responses ###\n\nIt's also possible to dynamically generate the response text upon each\nrequest by implementing a callback function on the `response` parameter:\n\n```javascript\n$.mockjax({\n  url: \"/restful/webservice\",\n  dataType: \"json\",\n  response: function(settings) {\n    this.responseText = {\n      randomText: \"random \" + Math.random()\n    };\n  }\n});\n```\n\n### Data Types ###\n\nMany of the examples above mock a `json` response. You can also mock `xml`:\n\n```javascript\n$.mockjax({\n  url: \"/some/xml\",\n  dataType: \"xml\",\n  responseXML: \"\u003cdocument\u003e\u003csay\u003eHello world XML\u003c/say\u003e\u003c/document\u003e\"\n});\n```\n\n(Don't forget that it's likely you'll need the [`xmlDOM`](http://github.com/jakerella/jquery-xmldom) library as well!)\n\nAnd `html`:\n\n```javascript\n$.mockjax({\n  url: \"/some/webservice\",\n  dataType: \"html\",\n  responseText: \"\u003cdiv\u003eHello there\u003c/div\u003e\"\n});\n```\n\n### Performing Actions After Request Completion ###\n\nIf you need to perform some actions after a call has completed you can\nuse one of the `onAfter{Xxxxx}` options. For example, to fire a method when\na request completes (either successfully or not):\n\n```javascript\n$.mockjax({\n  url: \"/api/end/point\",\n  onAfterComplete: function() {\n    // do any required cleanup\n  }\n});\n```\n\n### Globally Defining Mockjax Settings ###\n\nIt is also possible to define the global defaults for all Mockjax\nrequests by overwriting the `$.mockjaxSettings` object. By default the\nsettings are as follows:\n\n```javascript\n{\n  log:             null,  // DEPRECATED, use $.mockjaxSettings.logger instead\n  logger:          window.console,\n  logging:         2,\n  logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],\n  namespace:       null,\n  status:          200,\n  statusText:      \"OK\",\n  responseTime:    500,\n  isTimeout:       false,\n  throwUnmocked:   false,\n  retainAjaxCalls: true,\n  contentType:     \"text/plain\",\n  response:        \"\",\n  responseText:    \"\",\n  responseXML:     \"\",\n  proxy:           \"\",\n  proxyType:       \"GET\",\n  lastModified:    null,\n  etag:            \"\",\n  headers: {\n    etag: \"IJF@H#@923uf8023hFO@I#H#\",\n    \"content-type\" : \"text/plain\"\n  }\n}\n```\n\nTo overwrite a particular settings such as the default `content-type`, you\nwould do the following:\n\n```javascript\n$.mockjaxSettings.contentType = \"application/json\";\n```\n\n### Setting a Global URL Namespace ###\n\nThe namespace option in `$.mockjaxSettings` allows you to apply a prefix to\nall of your mocked urls, such as `/api/v1`.\n\n```javascript\n$.mockjaxSettings.namespace = \"/api/v1\";\n```\n\nThen the following mock will match `/api/v1/rest`:\n\n```javascript\n$.mockjax({\n    url: \"/rest\"\n})\n```\n\nAs will the following RegExp pattern:\n```javascript\n$.mockjax({\n    url: /^\\/rest$/\n})\n```\n\nThe global namespace option can also be overwritten on a particular mock.\n\n```javascript\n$.mockjax({\n    url: \"/rest-2\",\n    namespace: null\n})\n```\n\nNote that the namespace prefix does not apply to proxies.\n\n### Globally defining match order\n\nBy default, Mockjax matches requests in registration order (mockjax considers\nthe handlers registered first before handlers registered last). To reverse this\nbehavior:\n\n```javascript\n$.mockjaxSettings.matchInRegistrationOrder = false;\n```\n\nSetting `matchInRegistrationOrder` to `false` lets you override previously defined\nhandlers. Suppose you had:\n\n```javascript\n$.mockjax({\n    url: \"/rest\",\n    responseText: \"hello\"\n});\n$.mockjax({\n    url: \"/rest\",\n    responseText: \"byebye\"\n});\n```\n\nThe default behavior is that Mockjax returns `\"hello\"`, but with `matchInRegistrationOrder`\nset to `false`, Mockjax would return `\"byebye\"`.\n\nThis behavior allows you to override older handlers after they are initially set.\n\n### Removing Mockjax Handlers ###\n\nIf you need to reset the Mockjax handlers you've added, just call\n`$.mockjax.clear()`. _This will NOT reset the `$.mockjaxSettings`!_\n\n```javascript\n$.mockjax.clear();\n```\n\nYou can also clear individual mock handlers using their ID:\n\n```javascript\nvar id = $.mockjax({\n   ...\n});\n\n$.mockjax.clear(id);\n```\n\nOr you can clear a handler by the URL that it matches with either a String or RegExp:\n\n```javascript\n$.mockjax({\n   url: \"/api/foo\",\n   ...\n});\n\n$.mockjax.clear(\"/api/foo\");\n// or\n$.mockjax.clear(/foo/);\n```\n\n\n## Miscellaneous Information ##\n\n### jQuery Version Support ###\n\nWe strive to ensure that Mockjax is tested on the furthest patch version of all\nminor versions of jQuery (1.x.y through 3.x.y). In other words, we don't test \n1.12.1, but rather 1.12.4 (the furthest patch version on the 1.x line). The QUnit \ntests in the `/test` directory include links to each version of jQuery tested in \nthe header.\n\n### Browsers Tested ###\n\nWe use [BrowserStack](https://www.browserstack.com)'s awesome open source\ncollaboration to test Mockjax in real browsers using VMs on their platform. We\nrun all of our tests on the current versions of the major browsers below:\n\n* Edge\n* Firefox\n* Chrome\n* Safari\n\n### Using Mockjax in Other Ways ###\n\nYou can use Mockjax as a Node module or with Browserify... and presumably in \nother ways as well. We have tests for Node and Browserify. When using Mockjax \nas a Node module (including with Browserify), \n**you must provide the module with the jQuery library and a `window`**. \nHere is an example using a module intended for use as a \"browserified\" module:\n\n```js\nconst jquery = require('jquery');\nconst mockjax = require('jquery-mockjax')(jquery, window);\n// Note that we expect `window` to be defined once this file is browserified and\n// used in a browser. If it isn't Mockjax will have a problem!\n\nmockjax({\n    url: '/resource',\n    responseText: 'content'\n});\n\nfunction getResource(cb) {\n    jquery.ajax({\n        url: '/resource',\n        success: cb,\n        error: cb\n    });\n}\n```\n\n\n### Logging ###\n\nMockjax logs various pieces of information to the `console` (on `window`) in\nbrowsers, or to stdout in Node). You can customize various aspects of the\nlogging to suit your needs. By default, only 'error', 'warn' or 'info' messages\nwill be shown, but detailed information may be available in debug logs. Below\nare some common things you might need to do to get better logging information.\n\n#### Show different levels of log messages\n\n```js\n$.mockjaxSettings.logging = 4;  // very verbose debug messages\n$.mockjaxSettings.logging = 3;  // verbose log messages\n$.mockjaxSettings.logging = 2;  // informational messages\n$.mockjaxSettings.logging = 1;  // warning messages\n$.mockjaxSettings.logging = 0;  // only critical error messages\n```\n\n(Note that each level enables that level plus any lower number... thus setting\nlogging to `2` also enables warnings and errors.)\n\n#### Implement a custom logger\n\nIf you don't want to use the `console` object, you can pass in your own logging\nimplementation with the `logger` setting. Note that your logger must either\nimplement the `debug`, `log`, `info`, `warn`, and `error` methods, or you must\nalso provide what methods map to the 5 levels (0 through 4).\n\n```js\n$.mockjaxSettings.logger = {\n  debug: function() { ... },\n  log: function() { ... },\n  // ...\n};\n```\n\nYour logger methods may receive any number of arguments to log out, either as\nstrings or objects, similar to how the `window.console` object methods work.\n\nIf you have a logger that uses different methods names, specify them in this array:\n\n```js\n$.mockjaxSettings.logLevelMethods = ['critical', 'bad', 'stuff', 'log', 'verbose'];\n```\n\nNote that the first entry in this array (index `0`) will be errors while the last\nentry will be verbose output. Anything beyond index `4` will be ignored.\n\n#### What about the old `log` setting?\n\nThis was an undocumented feature whereby you could provide a `log` method using\n`$.mockjaxSettings`, however, it is no longer used internally.\n\n### Release History ###\n\nPlease read the [CHANGELOG](https://github.com/jakerella/jquery-mockjax/blob/master/CHANGELOG.md)\nfor a list of changes per release.\n\nNote that all releases are tagged in Github for easy reference, the `master` branch\nshould _not_ be considered a stable release!\n\n### License ###\n\nCopyright (c) 2014-2026 Jordan Kasper, formerly appendTo\n\nNOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 2014\n\nLicensed under the MIT license: [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT)\n\n### Contributing ###\n\nWe welcome any contributions by the community, whether in the form of a Pull\nRequest, issue submission and comments, or just sharing on social media!\n\nIf you want to contribute code to the project, please read our\n[Contribution guidelines](CONTRIBUTING.md) to see what you need to do to get your\nPull Request ready for merging.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjakerella%2Fjquery-mockjax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjakerella%2Fjquery-mockjax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjakerella%2Fjquery-mockjax/lists"}