Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for request cancellation using AbortController #47

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
* @property {Array<(body: any, headers: Headers) => any?>} [transformRequest] An array of transformations to apply to the outgoing request
* @property {string} [baseURL] a base URL from which to resolve all URLs
* @property {typeof window.fetch} [fetch] Custom window.fetch implementation
* @property {AbortSignal} [signal] Signal returned by AbortController
* @property {any} [data]
*/

Expand Down Expand Up @@ -195,7 +196,8 @@ export default (function create(/** @type {Options} */ defaults) {
method: _method || options.method,
body: data,
headers: deepMerge(options.headers, customHeaders, true),
credentials: options.withCredentials ? 'include' : undefined
credentials: options.withCredentials ? 'include' : undefined,
signal: options.signal
}).then((res) => {
for (const i in res) {
if (typeof res[i] != 'function') response[i] = res[i];
Expand Down
19 changes: 19 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,23 @@ describe('redaxios', () => {
expect(fetchMock).toHaveBeenCalledWith('/foo?e=iamthelaw', jasmine.any(Object));
});
});

describe('options.signal', () => {
it('should cancel a request when signal is passed', async () => {
const cancelToken = new axios.CancelToken();

const axiosGet = axios.get(jsonExample, {
signal: cancelToken.signal
});
cancelToken.abort();

const spy = jasmine.createSpy();
await axiosGet.catch(spy);

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(
jasmine.objectContaining({ code: 20, message: 'The user aborted a request.', name: 'AbortError' })
);
});
});
});