{"id":13493406,"url":"https://github.com/ctimmerm/axios-mock-adapter","last_synced_at":"2025-05-12T13:27:05.500Z","repository":{"id":37458390,"uuid":"54378064","full_name":"ctimmerm/axios-mock-adapter","owner":"ctimmerm","description":"Axios adapter that allows to easily mock requests","archived":false,"fork":false,"pushed_at":"2025-03-29T04:39:41.000Z","size":1234,"stargazers_count":3512,"open_issues_count":91,"forks_count":254,"subscribers_count":27,"default_branch":"master","last_synced_at":"2025-04-23T07:04:23.772Z","etag":null,"topics":["axios","javascript","mock","mocking"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ctimmerm.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-03-21T10:00:22.000Z","updated_at":"2025-04-21T20:00:40.000Z","dependencies_parsed_at":"2024-06-18T10:58:25.341Z","dependency_job_id":"2a3dee13-fa87-4272-93d9-d4e0225e5541","html_url":"https://github.com/ctimmerm/axios-mock-adapter","commit_stats":{"total_commits":253,"total_committers":73,"mean_commits":"3.4657534246575343","dds":"0.46640316205533594","last_synced_commit":"32074d6b866e304f6923abb5e6fa853eebcdd375"},"previous_names":[],"tags_count":40,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ctimmerm%2Faxios-mock-adapter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ctimmerm%2Faxios-mock-adapter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ctimmerm%2Faxios-mock-adapter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ctimmerm%2Faxios-mock-adapter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ctimmerm","download_url":"https://codeload.github.com/ctimmerm/axios-mock-adapter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253746994,"owners_count":21957671,"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":["axios","javascript","mock","mocking"],"created_at":"2024-07-31T19:01:14.886Z","updated_at":"2025-05-12T13:27:05.477Z","avatar_url":"https://github.com/ctimmerm.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Packages"],"sub_categories":["HTTP Request"],"readme":"# axios-mock-adapter\n\nAxios adapter that allows to easily mock requests\n\n## Installation\n\nUsing npm:\n\n`$ npm install axios-mock-adapter --save-dev`\n\nIt's also available as a UMD build:\n\n- https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.js\n- https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.min.js\n\naxios-mock-adapter works on Node as well as in a browser, it works with axios v0.17.0 and above.\n\n## Example\n\nMocking a `GET` request\n\n```js\nconst axios = require(\"axios\");\nconst AxiosMockAdapter = require(\"axios-mock-adapter\");\n\n// This sets the mock adapter on the default instance\nconst mock = new AxiosMockAdapter(axios);\n\n// Mock any GET request to /users\n// arguments for reply are (status, data, headers)\nmock.onGet(\"/users\").reply(200, {\n  users: [{ id: 1, name: \"John Smith\" }],\n});\n\naxios.get(\"/users\").then(function (response) {\n  console.log(response.data);\n});\n```\n\nMocking a `GET` request with specific parameters\n\n```js\nconst axios = require(\"axios\");\nconst AxiosMockAdapter = require(\"axios-mock-adapter\");\n\n// This sets the mock adapter on the default instance\nconst mock = new AxiosMockAdapter(axios);\n\n// Mock GET request to /users when param `searchText` is 'John'\n// arguments for reply are (status, data, headers)\nmock.onGet(\"/users\", { params: { searchText: \"John\" } }).reply(200, {\n  users: [{ id: 1, name: \"John Smith\" }],\n});\n\naxios\n  .get(\"/users\", { params: { searchText: \"John\" } })\n  .then(function (response) {\n    console.log(response.data);\n  });\n```\n\nWhen using `params`, you must match _all_ key/value pairs passed to that option.\n\nTo add a delay to responses, specify a delay amount (in milliseconds) when instantiating the adapter\n\n```js\n// All requests using this instance will have a 2 seconds delay:\nconst mock = new AxiosMockAdapter(axiosInstance, { delayResponse: 2000 });\n```\n\nYou can restore the original adapter (which will remove the mocking behavior)\n\n```js\nmock.restore();\n```\n\nYou can also reset the registered mock handlers with `resetHandlers`\n\n```js\nmock.resetHandlers();\n```\n\nYou can reset both registered mock handlers and history items with `reset`\n\n```js\nmock.reset();\n```\n\n`reset` is different from `restore` in that `restore` removes the mocking from the axios instance completely,\nwhereas `reset` only removes all mock handlers that were added with onGet, onPost, etc. but leaves the mocking in place.\n\nMock a low level network error\n\n```js\n// Returns a failed promise with Error('Network Error');\nmock.onGet(\"/users\").networkError();\n\n// networkErrorOnce can be used to mock a network error only once\nmock.onGet(\"/users\").networkErrorOnce();\n```\n\nMock a network timeout\n\n```js\n// Returns a failed promise with Error with code set to 'ECONNABORTED'\nmock.onGet(\"/users\").timeout();\n\n// timeoutOnce can be used to mock a timeout only once\nmock.onGet(\"/users\").timeoutOnce();\n```\n\nPassing a function to `reply`\n\n```js\nmock.onGet(\"/users\").reply(function (config) {\n  // `config` is the axios config and contains things like the url\n\n  // return an array in the form of [status, data, headers]\n  return [\n    200,\n    {\n      users: [{ id: 1, name: \"John Smith\" }],\n    },\n  ];\n});\n```\n\nPassing a function to `reply` that returns an axios request, essentially mocking a redirect\n\n```js\nmock.onPost(\"/foo\").reply(function (config) {\n  return axios.get(\"/bar\");\n});\n```\n\nUsing a regex\n\n```js\nmock.onGet(/\\/users\\/\\d+/).reply(function (config) {\n  // the actual id can be grabbed from config.url\n\n  return [200, {}];\n});\n```\n\nUsing variables in regex\n\n```js\nconst usersUri = \"/users\";\nconst url = new RegExp(`${usersUri}/*`);\n\nmock.onGet(url).reply(200, users);\n```\n\nSpecify no path to match by verb alone\n\n```js\n// Reject all POST requests with HTTP 500\nmock.onPost().reply(500);\n```\n\nChaining is also supported\n\n```js\nmock.onGet(\"/users\").reply(200, users).onGet(\"/posts\").reply(200, posts);\n```\n\n`.replyOnce()` can be used to let the mock only reply once\n\n```js\nmock\n  .onGet(\"/users\")\n  .replyOnce(200, users) // After the first request to /users, this handler is removed\n  .onGet(\"/users\")\n  .replyOnce(500); // The second request to /users will have status code 500\n// Any following request would return a 404 since there are\n// no matching handlers left\n```\n\nMocking any request to a given url\n\n```js\n// mocks GET, POST, ... requests to /foo\nmock.onAny(\"/foo\").reply(200);\n```\n\n`.onAny` can be useful when you want to test for a specific order of requests\n\n```js\n// Expected order of requests:\nconst responses = [\n  [\"GET\", \"/foo\", 200, { foo: \"bar\" }],\n  [\"POST\", \"/bar\", 200],\n  [\"PUT\", \"/baz\", 200],\n];\n\n// Match ALL requests\nmock.onAny().reply((config) =\u003e {\n  const [method, url, ...response] = responses.shift();\n  if (config.url === url \u0026\u0026 config.method.toUpperCase() === method)\n    return response;\n  // Unexpected request, error out\n  return [500, {}];\n});\n```\n\nRequests that do not map to a mock handler are rejected with a HTTP 404 response. Since\nhandlers are matched in order, a final `onAny()` can be used to change the default\nbehaviour\n\n```js\n// Mock GET requests to /foo, reject all others with HTTP 500\nmock.onGet(\"/foo\").reply(200).onAny().reply(500);\n```\n\nMocking a request with a specific request body/data\n\n```js\nmock.onPut(\"/product\", { id: 4, name: \"foo\" }).reply(204);\n```\n\nUsing an asymmetric matcher, for example Jest matchers\n\n```js\nmock\n  .onPost(\n    \"/product\",\n    { id: 1 },\n    {\n      headers: expect.objectContaining({\n        Authorization: expect.stringMatching(/^Basic /),\n      })\n    }\n  )\n  .reply(204);\n```\n\nUsing a custom asymmetric matcher (any object that has a `asymmetricMatch` property)\n\n```js\nmock\n  .onPost(\"/product\", {\n    asymmetricMatch: function (actual) {\n      return [\"computer\", \"phone\"].includes(actual[\"type\"]);\n    },\n  })\n  .reply(204);\n```\n\n`.passThrough()` forwards the matched request over network\n\n```js\n// Mock POST requests to /api with HTTP 201, but forward\n// GET requests to server\nmock\n  .onPost(/^\\/api/)\n  .reply(201)\n  .onGet(/^\\/api/)\n  .passThrough();\n```\n\nRecall that the order of handlers is significant\n\n```js\n// Mock specific requests, but let unmatched ones through\nmock\n  .onGet(\"/foo\")\n  .reply(200)\n  .onPut(\"/bar\", { xyz: \"abc\" })\n  .reply(204)\n  .onAny()\n  .passThrough();\n```\n\nNote that `passThrough` requests are not subject to delaying by `delayResponse`.\n\nIf you set `onNoMatch` option to `passthrough` all requests would be forwarded over network by default\n\n```js\n// Mock all requests to /foo with HTTP 200, but forward\n// any others requests to server\nconst mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: \"passthrough\" });\n\nmock.onAny(\"/foo\").reply(200);\n```\n\nUsing `onNoMatch` option with `throwException` to throw an exception when a request is made without match any handler. It's helpful to debug your test mocks.\n\n```js\nconst mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: \"throwException\" });\n\nmock.onAny(\"/foo\").reply(200);\n\naxios.get(\"/unexistent-path\");\n\n// Exception message on console:\n//\n// Could not find mock for: \n// {\n//   \"method\": \"get\",\n//   \"url\": \"http://localhost/unexistent-path\"\n// }\n```\n\nAs of 1.7.0, `reply` function may return a Promise:\n\n```js\nmock.onGet(\"/product\").reply(function (config) {\n  return new Promise(function (resolve, reject) {\n    setTimeout(function () {\n      if (Math.random() \u003e 0.1) {\n        resolve([200, { id: 4, name: \"foo\" }]);\n      } else {\n        // reject() reason will be passed as-is.\n        // Use HTTP error status code to simulate server failure.\n        resolve([500, { success: false }]);\n      }\n    }, 1000);\n  });\n});\n```\n\nComposing from multiple sources with Promises:\n\n```js\nconst normalAxios = axios.create();\nconst mockAxios = axios.create();\nconst mock = new AxiosMockAdapter(mockAxios);\n\nmock\n  .onGet(\"/orders\")\n  .reply(() =\u003e\n    Promise.all([\n      normalAxios.get(\"/api/v1/orders\").then((resp) =\u003e resp.data),\n      normalAxios.get(\"/api/v2/orders\").then((resp) =\u003e resp.data),\n      { id: \"-1\", content: \"extra row 1\" },\n      { id: \"-2\", content: \"extra row 2\" },\n    ]).then((sources) =\u003e [\n      200,\n      sources.reduce((agg, source) =\u003e agg.concat(source)),\n    ])\n  );\n```\n\n## History\n\nThe `history` property allows you to enumerate existing axios request objects. The property is an object of verb keys referencing arrays of request objects.\n\nThis is useful for testing.\n\n```js\ndescribe(\"Feature\", () =\u003e {\n  it(\"requests an endpoint\", (done) =\u003e {\n    const mock = new AxiosMockAdapter(axios);\n    mock.onPost(\"/endpoint\").replyOnce(200);\n\n    feature\n      .request()\n      .then(() =\u003e {\n        expect(mock.history.post.length).toBe(1);\n        expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: \"bar\" }));\n      })\n      .then(done)\n      .catch(done.fail);\n  });\n});\n```\n\nYou can clear the history with `resetHistory`\n\n```js\nmock.resetHistory();\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fctimmerm%2Faxios-mock-adapter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fctimmerm%2Faxios-mock-adapter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fctimmerm%2Faxios-mock-adapter/lists"}