### Install axios-mock-adapter using npm Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md This command installs the axios-mock-adapter package as a development dependency using npm. It's required to use the library in your project. ```Shell $ npm install axios-mock-adapter --save-dev ``` -------------------------------- ### Mocking a Basic GET Request Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to set up `axios-mock-adapter` on the default Axios instance and mock a simple GET request to a specific URL (`/users`), returning a 200 status with predefined user data. It also shows how to make the actual Axios request and log the mocked response. ```js const axios = require("axios"); const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance const mock = new AxiosMockAdapter(axios); // Mock any GET request to /users // arguments for reply are (status, data, headers) mock.onGet("/users").reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios.get("/users").then(function (response) { console.log(response.data); }); ``` -------------------------------- ### Mocking a GET Request with Specific Parameters Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates how to mock a GET request that includes specific query parameters (e.g., `searchText: 'John'`). The mock will only activate if the incoming request matches these exact parameters. It also includes the corresponding Axios request to trigger the mock. ```js const axios = require("axios"); const AxiosMockAdapter = require("axios-mock-adapter"); // This sets the mock adapter on the default instance const mock = new AxiosMockAdapter(axios); // Mock GET request to /users when param `searchText` is 'John' // arguments for reply are (status, data, headers) mock.onGet("/users", { params: { searchText: "John" } }).reply(200, { users: [{ id: 1, name: "John Smith" }], }); axios .get("/users", { params: { searchText: "John" } }) .then(function (response) { console.log(response.data); }); ``` -------------------------------- ### Dynamic Reply with Promise-Based Responses Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates how the `reply` function can return a Promise, allowing for asynchronous and dynamic response generation. This example simulates a network delay and randomly resolves with a success (200) or failure (500) status. ```js mock.onGet("/product").reply(function (config) { return new Promise(function (resolve, reject) { setTimeout(function () { if (Math.random() > 0.1) { resolve([200, { id: 4, name: "foo" }]); } else { // reject() reason will be passed as-is. // Use HTTP error status code to simulate server failure. resolve([500, { success: false }]); } }, 1000); }); }); ``` -------------------------------- ### Understanding Handler Order and `onAny().passThrough()` Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains the significance of handler order in Axios Mock Adapter. It demonstrates how to mock specific GET and PUT requests, and then use `onAny().passThrough()` to forward any unmatched requests to the server. ```js // Mock specific requests, but let unmatched ones through mock .onGet("/foo") .reply(200) .onPut("/bar", { xyz: "abc" }) .reply(204) .onAny() .passThrough(); ``` -------------------------------- ### Forwarding Matched Requests with `.passThrough()` Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows how to mock specific requests (e.g., POST to `/api` with 201 status) while allowing other matched requests (e.g., GET to `/api`) to be forwarded over the network using `.passThrough()`. ```js // Mock POST requests to /api with HTTP 201, but forward // GET requests to server mock .onPost(/^\/api/) .reply(201) .onGet(/^\/api/) .passThrough(); ``` -------------------------------- ### Configuring Default Passthrough for Unmatched Requests Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to initialize `AxiosMockAdapter` with `onNoMatch: 'passthrough'` to automatically forward all requests that do not match any defined mock handlers over the network. This example mocks only requests to `/foo`. ```js // Mock all requests to /foo with HTTP 200, but forward // any others requests to server const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "passthrough" }); mock.onAny("/foo").reply(200); ``` -------------------------------- ### Mocking Any HTTP Method for a URL with onAny Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates `onAny()`, which allows mocking requests to a specific URL regardless of the HTTP method (GET, POST, PUT, etc.). This simplifies broad URL-based mocking where the method is not a primary concern. ```js // mocks GET, POST, ... requests to /foo mock.onAny("/foo").reply(200); ``` -------------------------------- ### Mocking a Network Error Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Provides examples of `networkError()` and `networkErrorOnce()` to simulate a low-level network failure. This causes the request promise to reject with an `Error('Network Error')`, mimicking connectivity issues. `networkErrorOnce()` applies the error only for the first matching request. ```js // Returns a failed promise with Error('Network Error'); mock.onGet("/users").networkError(); // networkErrorOnce can be used to mock a network error only once mock.onGet("/users").networkErrorOnce(); ``` -------------------------------- ### Matching URLs with Regular Expressions Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to use a regular expression with `onGet()` to match a pattern of URLs (e.g., `/users/\d+/`). This allows for flexible URL matching and the extraction of dynamic parts like IDs from `config.url` within the reply function. ```js mock.onGet(/\/users\/\d+/).reply(function (config) { // the actual id can be grabbed from config.url return [200, {}]; }); ``` -------------------------------- ### Dynamic Regex Matching with Variables Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates how to construct a regular expression using JavaScript variables. This makes URL matching more dynamic and reusable for `onGet()` or other `on` methods, especially when parts of the URL path are defined elsewhere. ```js const usersUri = "/users"; const url = new RegExp(`${usersUri}/*`); mock.onGet(url).reply(200, users); ``` -------------------------------- ### Dynamic Reply with a Function Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains how to pass a function to `reply()`, allowing for dynamic response generation based on the request `config` object. The function receives the Axios config and should return an array in the form of `[status, data, headers]`. ```js mock.onGet("/users").reply(function (config) { // `config` is the axios config and contains things like the url // return an array in the form of [status, data, headers] return [ 200, { users: [{ id: 1, name: "John Smith" }], }, ]; }); ``` -------------------------------- ### Single-Use Mock Responses with replyOnce Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates `replyOnce()`, which makes a mock handler active for only one request. After the first matching request, this handler is removed. Subsequent requests to the same URL will not use this handler, potentially falling through to other mocks or a 404. ```js mock .onGet("/users") .replyOnce(200, users) // After the first request to /users, this handler is removed .onGet("/users") .replyOnce(500); // The second request to /users will have status code 500 // Any following request would return a 404 since there are // no matching handlers left ``` -------------------------------- ### Composing Mock Responses from Multiple Asynchronous Sources Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates an advanced use case where a mock reply is composed by combining data from multiple asynchronous sources (e.g., other Axios requests) using `Promise.all`. The results are then aggregated and returned as a single mock response. ```js const normalAxios = axios.create(); const mockAxios = axios.create(); const mock = new AxiosMockAdapter(mockAxios); mock .onGet("/orders") .reply(() => Promise.all([ normalAxios.get("/api/v1/orders").then((resp) => resp.data), normalAxios.get("/api/v2/orders").then((resp) => resp.data), { id: "-1", content: "extra row 1" }, { id: "-2", content: "extra row 2" }, ]).then((sources) => [ 200, sources.reduce((agg, source) => agg.concat(source)), ]) ); ``` -------------------------------- ### Mocking a Redirect by Returning an Axios Request Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows an advanced use case where the `reply` function returns an actual Axios request. This effectively simulates a redirect or proxying behavior within the mock, allowing one mocked request to trigger another internal Axios call. ```js mock.onPost("/foo").reply(function (config) { return axios.get("/bar"); }); ``` -------------------------------- ### Mocking Request Headers with `expect.objectContaining` Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to mock a POST request to `/login` and assert that the request headers contain an `Authorization` header matching a basic authentication pattern using `expect.objectContaining` and `expect.stringMatching`. ```js headers: expect.objectContaining({ Authorization: expect.stringMatching(/^Basic /), }) } ) .reply(204); ``` -------------------------------- ### Matching Requests by HTTP Verb Only Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows how to mock all requests for a specific HTTP verb (e.g., `POST`) without specifying a URL path. This is useful for catching all requests of a certain type, regardless of their endpoint, and applying a general response. ```js // Reject all POST requests with HTTP 500 mock.onPost().reply(500); ``` -------------------------------- ### Chaining Multiple Mock Handlers Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains that chaining multiple `onGet()` or other `on` methods is supported. This allows for concise definition of multiple distinct mock responses in a single, fluent statement. ```js mock.onGet("/users").reply(200, users).onGet("/posts").reply(200, posts); ``` -------------------------------- ### Dynamic Response Ordering with onAny Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows an advanced use of `onAny()` combined with a dynamic `reply` function to enforce a specific order of expected requests and provide corresponding responses. This is useful for complex test scenarios where request sequence matters. ```js // Expected order of requests: const responses = [ ["GET", "/foo", 200, { foo: "bar" }], ["POST", "/bar", 200], ["PUT", "/baz", 200], ]; // Match ALL requests mock.onAny().reply((config) => { const [method, url, ...response] = responses.shift(); if (config.url === url && config.method.toUpperCase() === method) return response; // Unexpected request, error out return [500, {}]; }); ``` -------------------------------- ### Customizing Default 404 Behavior with onAny Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains how to use a final `onAny()` handler to catch all requests that do not match any preceding specific mocks. This allows for a custom default response (e.g., HTTP 500) instead of the standard 404 for unmatched requests. ```js // Mock GET requests to /foo, reject all others with HTTP 500 mock.onGet("/foo").reply(200).onAny().reply(500); ``` -------------------------------- ### Using Asymmetric Matchers for Request Body Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates the use of asymmetric matchers (e.g., Jest matchers) within the request body configuration. This provides more flexible and powerful matching capabilities for complex data structures in the request payload. ```js mock .onPost( "/product", { id: 1 }, { ``` -------------------------------- ### Adding a Response Delay to Axios Mock Adapter Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to configure `axios-mock-adapter` to introduce a delay (in milliseconds) for all mocked responses. This is useful for simulating network latency in tests or development environments. ```js // All requests using this instance will have a 2 seconds delay: const mock = new AxiosMockAdapter(axiosInstance, { delayResponse: 2000 }); ``` -------------------------------- ### Accessing Request History for Testing Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains how to use the `history` property of `AxiosMockAdapter` to inspect past requests. This is particularly useful for testing scenarios where you need to assert that specific requests were made, including their method, URL, and data. ```js describe("Feature", () => { it("requests an endpoint", (done) => { const mock = new AxiosMockAdapter(axios); mock.onPost("/endpoint").replyOnce(200); feature .request() .then(() => { expect(mock.history.post.length).toBe(1); expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" })); }) .then(done) .catch(done.fail); }); }); ``` -------------------------------- ### Mocking a Network Timeout Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to use `timeout()` and `timeoutOnce()` to simulate a request timeout. This results in a rejected promise with an `Error` object containing `code: 'ECONNABORTED'`, mimicking a request that took too long to respond. `timeoutOnce()` applies the timeout only for the first matching request. ```js // Returns a failed promise with Error with code set to 'ECONNABORTED' mock.onGet("/users").timeout(); // timeoutOnce can be used to mock a timeout only once mock.onGet("/users").timeoutOnce(); ``` -------------------------------- ### Restoring Axios to Original Behavior Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Explains how to use `mock.restore()` to completely remove the mocking behavior from the Axios instance, reverting it to its original state where requests are sent to actual network endpoints. ```js mock.restore(); ``` -------------------------------- ### Throwing Exceptions for Unmatched Requests with `onNoMatch` Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows how to configure `AxiosMockAdapter` with `onNoMatch: 'throwException'` to throw an error when a request is made that doesn't match any mock handler. This is useful for debugging tests by explicitly failing when unexpected requests occur. ```js const mock = new AxiosMockAdapter(axiosInstance, { onNoMatch: "throwException" }); mock.onAny("/foo").reply(200); axios.get("/unexistent-path"); // Exception message on console: // // Could not find mock for: // { // "method": "get", // "url": "http://localhost/unexistent-path" // } ``` -------------------------------- ### Using Custom Asymmetric Matchers for Request Body Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates how to use a custom asymmetric matcher function to validate the request body. The `asymmetricMatch` property allows defining a function that returns `true` if the actual request data matches the desired criteria, in this case, checking if the `type` property is 'computer' or 'phone'. ```js mock .onPost("/product", { asymmetricMatch: function (actual) { return ["computer", "phone"].includes(actual["type"]); }, }) .reply(204); ``` -------------------------------- ### Mocking Requests with Specific Request Body/Data Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Demonstrates how to mock a PUT request that requires a specific request body (data payload) to match. The mock will only trigger for requests that send the exact data specified in the second argument. ```js mock.onPut("/product", { id: 4, name: "foo" }).reply(204); ``` -------------------------------- ### Resetting Registered Mock Handlers Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows how to use `mock.resetHandlers()` to clear all previously registered mock handlers (e.g., `onGet`, `onPost`) while keeping the adapter active on the Axios instance. This allows for re-registering new mocks without fully restoring Axios. ```js mock.resetHandlers(); ``` -------------------------------- ### Resetting Mock Handlers and Request History Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Illustrates how `mock.reset()` clears both registered mock handlers and any recorded request history. This provides a clean slate for new mocks and history tracking, similar to `resetHandlers` but also clearing history. ```js mock.reset(); ``` -------------------------------- ### Clearing Request History with `resetHistory()` Source: https://github.com/ctimmerm/axios-mock-adapter/blob/master/README.md Shows how to clear the recorded request history using the `resetHistory()` method of `AxiosMockAdapter`. This is useful for resetting the state between tests or specific test phases. ```js mock.resetHistory(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.