or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

error-simulation.mdhttp-methods.mdindex.mdmock-adapter.mdresponses.md
tile.json

responses.mddocs/

Response Configuration

Flexible response configuration with support for static responses, dynamic functions, and various response formats. The RequestHandler interface provides methods for configuring how mocked requests should respond.

Capabilities

Reply Method

Sets a reusable mock response that will be used for all matching requests.

/**
 * Set mock response (reusable for multiple requests)
 * @param statusOrCallback - HTTP status code or callback function
 * @param data - Response data (optional)
 * @param headers - Response headers (optional)
 * @returns AxiosMockAdapter for chaining
 */
reply(statusOrCallback, data?, headers?): AxiosMockAdapter;

Usage Examples:

// Simple status code
mock.onGet("/users").reply(200);

// With data
mock.onGet("/users").reply(200, [
  { id: 1, name: "John" },
  { id: 2, name: "Jane" }
]);

// With data and headers
mock.onGet("/users").reply(200, { users: [] }, { 
  "X-Total-Count": "0",
  "Content-Type": "application/json"
});

// Using callback function
mock.onGet("/users").reply(function (config) {
  return [200, { url: config.url }];
});

Reply Once Method

Sets a mock response that will only be used once, then automatically removed.

/**
 * Set mock response for single use only
 * @param statusOrCallback - HTTP status code or callback function
 * @param data - Response data (optional)
 * @param headers - Response headers (optional)
 * @returns AxiosMockAdapter for chaining
 */
replyOnce(statusOrCallback, data?, headers?): AxiosMockAdapter;

Usage Examples:

// First request succeeds, subsequent requests get different behavior
mock
  .onGet("/users")
  .replyOnce(200, [{ id: 1, name: "John" }])
  .onGet("/users")
  .replyOnce(500);

// After two requests, any further requests would return 404

With Delay Method

Adds artificial delay to responses to simulate network latency.

/**
 * Add delay to response in milliseconds
 * @param delay - Delay in milliseconds
 * @returns RequestHandler with delay configured
 */
withDelayInMs(delay: number): RequestHandler;

Usage Examples:

// Add 1 second delay
mock.onGet("/users").withDelayInMs(1000).reply(200, []);

// Chain with other methods
mock.onGet("/slow").withDelayInMs(2000).replyOnce(200);

// Random delay
mock.onGet("/api").withDelayInMs(Math.random() * 1000).reply(200);

Response Formats

Static Response Array

The most common format: [status, data, headers].

mock.onGet("/users").reply(200, { users: [] }, { "X-Count": "0" });

Static Response Object

Alternative object format with explicit properties.

interface MockObjectResponse {
  status: number;
  data: any;
  headers?: object;
  config?: object;
}

Usage Example:

mock.onGet("/users").reply(function (config) {
  return {
    status: 200,
    data: { users: [] },
    headers: { "X-Count": "0" },
    config: { url: "/users" }
  };
});

Callback Functions

Dynamic responses using callback functions that receive the axios config.

/**
 * Callback function for dynamic responses
 * @param config - Axios request configuration object
 * @returns MockResponse or Promise<MockResponse>
 */
type CallbackResponseSpecFunc = (config) => MockResponse | Promise<MockResponse>;

type MockResponse = [number, any?, object?] | {
  status: number;
  data: any;
  headers?: object;
  config?: object;
};

Usage Examples:

// Access request details
mock.onGet(/\/users\/(\d+)/).reply(function (config) {
  const id = config.url.match(/\/users\/(\d+)/)[1];
  return [200, { id: parseInt(id), name: `User ${id}` }];
});

// Dynamic status based on request
mock.onPost("/users").reply(function (config) {
  const user = JSON.parse(config.data);
  if (user.name) {
    return [201, { id: Date.now(), ...user }];
  } else {
    return [400, { error: "Name is required" }];
  }
});

// Access headers
mock.onGet("/protected").reply(function (config) {
  if (config.headers.Authorization) {
    return [200, { message: "Authorized" }];
  } else {
    return [401, { error: "Unauthorized" }];
  }
});

Promise-Based Responses

Callback functions can return promises for asynchronous response generation.

mock.onGet("/async").reply(function (config) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      if (Math.random() > 0.1) {
        resolve([200, { id: 4, name: "foo" }]);
      } else {
        resolve([500, { success: false }]);
      }
    }, 1000);
  });
});

Axios Request Responses

Callback functions can return axios requests for redirect-like behavior.

mock.onPost("/redirect").reply(function (config) {
  return axios.get("/actual-endpoint");
});

Response Composition

Multiple Sources with Promises

Combine multiple data sources in a single response.

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)),
    ])
  );

Sequential Responses

Configure different responses for subsequent requests to the same endpoint.

// First request returns users, second returns empty array
mock
  .onGet("/users")
  .replyOnce(200, [{ id: 1, name: "John" }])
  .onGet("/users")
  .reply(200, []);

Global Configuration

Global Response Delay

Set delay for all responses when creating the adapter.

const mock = new AxiosMockAdapter(axios, { delayResponse: 2000 });

// All responses will have 2 second delay
mock.onGet("/users").reply(200, []);
mock.onPost("/users").reply(201);

Note: Pass-through requests are not subject to delayResponse.

Default Fallback Behavior

Configure what happens when no mock handler matches a request.

// Return 404 for unmatched requests (default)
const mock = new AxiosMockAdapter(axios);

// Pass through unmatched requests to real network
const mockPassthrough = new AxiosMockAdapter(axios, { onNoMatch: "passthrough" });

// Throw exception for unmatched requests
const mockStrict = new AxiosMockAdapter(axios, { onNoMatch: "throwException" });

Advanced Patterns

Handler Priority

Handlers are matched in the order they were registered. More specific handlers should be registered first.

// Specific handler first
mock.onGet("/users/123").reply(200, { id: 123, name: "John" });

// General handler second
mock.onGet(/\/users\/\d+/).reply(200, { id: 0, name: "Default" });

Conditional Responses

Use callback functions for complex conditional logic.

mock.onPost("/api").reply(function (config) {
  const data = JSON.parse(config.data);
  
  // Different responses based on request content
  if (data.type === "user") {
    return [201, { id: 1, type: "user" }];
  } else if (data.type === "admin") {
    return [201, { id: 1, type: "admin", permissions: ["all"] }];
  } else {
    return [400, { error: "Invalid type" }];
  }
});

Response Headers

Include custom headers in responses for testing header-dependent logic.

mock.onGet("/api").reply(200, { data: "test" }, {
  "X-Rate-Limit": "100",
  "X-Rate-Remaining": "99",
  "Cache-Control": "max-age=3600",
  "ETag": '"123456"'
});