axios-mock-adapter

repository·master·Indexed 25 days ago

https://github.com/ctimmerm/axios-mock-adapter

An adapter for Axios that allows developers to easily mock network requests for testing environments. It enables the simulation of successful responses, errors, timeouts, and network delays without a real backend. It supports matching requests by URL, regex, or parameters, and provides tools to inspect request history and manage mock handlers.

Tokens
1.5K
Snippets
2
Records
14
Agent score
36%

What's inside axios-mock-adapter

  1. Initialize the AxiosMockAdapter

    master

    To start mocking, create a new instance of AxiosMockAdapter and pass your axios instance (either the default instance or a custom one) to the constructor.

    You can optionally configure a delayResponse in milliseconds to simulate network latency for all requests handled by this instance.

  2. Use .onAny() and .passThrough() for advanced routing

    master

    Match any method

    Use mock.onAny(url) to intercept any HTTP verb (GET, POST, etc.) for a specific URL.

    Forwarding requests

    • .passThrough(): Forwards the matched request to the actual network instead of mocking it. Note that passThrough requests are not affected by delayResponse.
    • onNoMatch: "passthrough": When initializing the adapter, setting this option will cause all requests that don't match a handler to be forwarded to the real server.
    • onNoMatch: "throwException": Throws an exception when a request is made that doesn't match any handler. This is useful for debugging.

    Note: Handlers are matched in the order they are registered.

  3. Install axios-mock-adapter

    master

    You can install axios-mock-adapter using npm as a development dependency. It works in both Node.js and browser environments and requires axios version 0.17.0 or above.

    Alternatively, you can use the UMD builds available via unpkg.

    $ npm install axios-mock-adapter --save-dev
  4. Simulate network errors and timeouts

    master

    You can simulate low-level network failures using specific methods:

    • .networkError(): Returns a failed promise with Error('Network Error').
    • .timeout(): Returns a failed promise with an error code set to 'ECONNABORTED'.

    Use .networkErrorOnce() or .timeoutOnce() to trigger these errors only for a single request.

  5. Manage mock handlers and state

    master

    Use these methods to control the lifecycle of your mocks:

    • mock.resetHandlers(): Removes all registered mock handlers (e.g., those created with onGet).
    • mock.reset(): Removes all registered mock handlers AND clears the request history.
    • mock.restore(): Completely removes the mocking behavior from the axios instance, restoring the original adapter.
    • mock.resetHistory(): Clears the recorded request history.
  6. Inspect request history

    master

    The history property allows you to inspect the requests that were made to the mock adapter. It is an object where keys are HTTP verbs (e.g., get, post) and values are arrays of the corresponding request objects.

    This is highly useful for assertions in testing environments.

    // After making a request...
    expect(mock.history.post.length).toBe(1);
    expect(mock.history.post[0].data).toBe(JSON.stringify({ foo: "bar" }));
  7. Configure response behavior with .reply()

    master

    The .reply() method defines what the mock returns. It accepts several forms:

    1. Static values: (status, data, headers).
    2. Function returning an array: (config) => [status, data, headers]. The config object contains the axios request configuration.
    3. Function returning a Promise: Useful for simulating async logic or composing data from multiple sources.
    4. Function returning an axios request: Used to mock redirects.

    Use .replyOnce() if you want the mock handler to be removed immediately after the first successful match.

  8. Mock HTTP requests with .onGet(), .onPost(), etc.

    master

    Use verb-specific methods like onGet, onPost, onPut, onDelete, etc., to intercept requests. You can match requests by URL, regex, or specific parameters.

    Matching criteria:

    • URL/Regex: Pass a string or a RegExp to the method.
    • Params: Pass an object to match specific query parameters. Note that you must match all key/value pairs provided.
    • Body/Data: Pass an object to match the request body.
    • Asymmetric Matchers: Use objects with an asymmetricMatch function or Jest matchers (like expect.objectContaining) to match request data partially.
  9. Define request responses with .reply()

    master

    After defining a matcher, use the .reply() method to specify the response. The response can be defined in several ways:

    1. Status and Data: .reply(status, data, headers)
    2. Status and Headers: .reply(status, null, headers)
    3. Function: .reply((config) => { ... }) — allows for dynamic responses based on the request configuration.

    Note: .reply() registers a handler that will be used for every subsequent matching request.

  10. Reset or Restore the mock adapter

    master

    Use these methods to manage the state of your mocks:

    • reset(): Clears all registered handlers and all request history.
    • resetHandlers(): Clears all registered handlers but keeps the request history.
    • resetHistory(): Clears the request history but keeps the registered handlers.
    • restore(): Removes the mock adapter from the axios instance and restores the original adapter.
  11. Initialize AxiosMockAdapter

    master

    To use axios-mock-adapter, instantiate the AxiosMockAdapter class by passing an existing axios instance. You can optionally provide an options object to configure behavior.

    Options:

    • delayResponse: A number representing the delay in milliseconds for responses. If set to 0 or less, it is treated as null.
    • onNoMatch: A callback function to execute when no handler matches a request.

    Note: The adapter replaces the axiosInstance.defaults.adapter with its own internal adapter to intercept requests.