-
Notifications
You must be signed in to change notification settings - Fork 21
Mocking API Responses
Nick Watts edited this page Aug 3, 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
-
- A function that accepts arguments to
-
fn
: A function that wrapsfetch
(accepts afetch
function and returns a newfetch
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
Terra UI Wiki.
- Getting Started
- Contributor Guide
- Intro to UI Development
- Troubleshooting Build Failures
- Editor Configuration
- BEEs
- Pull Requests
- How to Find a PR Site
- Feature Flags
- Mixpanel
- Cobranding and White-Label Sites
- Using Terra UI packages in other projects