Skip to content

Mocking API Responses

Josh Ladieu edited this page Sep 7, 2023 · 7 revisions

Unit tests can mock API calls, and other dependencies more directly with Jest’s module mocking capabilities.

But for tests in the Puppeteer test suite (end2end) or manual testing, the following pattern can be helpful.


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