Skip to content

Mocking API Responses

Nick Watts edited this page Jul 11, 2022 · 7 revisions

API responses can be mocked by setting window.ajaxOverridesStore.

The store should contain an array, where each item is an object with two properties:

  • filter: Determines which URLs to apply the override to. This can be specified in two ways:
    • A function that accepts arguments to fetch and returns a boolean
    • An object with two keys:
      • url: a regex matched against the request URL
      • method: (optional) a string compared against the request method
  • fn: A function that wraps fetch (accepts a fetch function and returns a new fetch function

For example:

window.ajaxOverridesStore.set([
  {
    filter: { url: /api\/billing\/v2$/ },
    fn: window.ajaxOverrideUtils.makeSuccess(projectListResult)
  }
]

window.ajaxOverrideUtils contains a few helpers for creating the fn function.

  • mapJsonBody: takes a function that transforms the original response body
  • makeError: takes an object with two keys:
    • status: status code for the mock response
    • frequency: (optional) number 0-1 that controls what proportion of responses are replaced with mock errors
  • makeSuccess: takes an object to return as the response
Clone this wiki locally