Skip to content

Commit

Permalink
Add aborted property to API responses
Browse files Browse the repository at this point in the history
This makes it easy to test whether an API request failed because it was aborted.
  • Loading branch information
robertknight committed Dec 6, 2024
1 parent 09ca2e4 commit 07f2e3b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
8 changes: 8 additions & 0 deletions h/static/scripts/group-forms/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ export class APIError extends Error {
this.response = response;
this.json = json;
}

/**
* Property that is true if the API call failed because the operation was
* aborted.
*/
get aborted() {
return this.cause?.name === 'AbortError';
}
}

export type APIOptions = {
Expand Down
19 changes: 18 additions & 1 deletion h/static/scripts/group-forms/utils/test/api-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('callAPI', () => {
});

afterEach(() => {
window.fetch.restore();
window.fetch.restore?.();
});

context('when the API responds successfully', () => {
Expand Down Expand Up @@ -138,6 +138,23 @@ describe('callAPI', () => {
assert.calledWith(fakeFetch, paginatedURL.toString());
});

it('rejects with aborted APIError if request is aborted', async () => {
window.fetch.restore();

const ac = new AbortController();
ac.abort();

let error;
try {
await callAPI(url, { signal: ac.signal });
} catch (e) {
error = e;
}

assert.instanceOf(error, APIError);
assert.isTrue(error.aborted);
});

[
{
response: new Response(
Expand Down

0 comments on commit 07f2e3b

Please sign in to comment.