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

Alternative AbortController support (#54) #137

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/index.mjs
Expand Up @@ -34,6 +34,14 @@ export default function(url, options) {
resolve(response());
};

if (options.signal) {
options.signal.addEventListener('abort', request.abort.bind(request));
}

request.onabort = () => {
reject(new DOMException('The user aborted a request.'));
};

request.onerror = reject;

request.withCredentials = options.credentials=='include';
Expand Down
58 changes: 58 additions & 0 deletions test/index.js
@@ -1,6 +1,26 @@
import { EventEmitter } from 'events';
import fetch from '../src/index.mjs';
import fetchDist from '..';

// node does not have abort and signal classes
class AbortSignal extends EventEmitter {
constructor() {
super();
this.addEventListener = jest.fn((type, callback) => {
this.on(type, callback);
});
}
}

class AbortController {
constructor() {
this.signal = new AbortSignal();
}
abort() {
this.signal.emit('abort');
}
}

describe('unfetch', () => {
it('should be a function', () => {
expect(fetch).toEqual(expect.any(Function));
Expand Down Expand Up @@ -80,5 +100,43 @@ describe('unfetch', () => {

return p;
});

it('respects abort signal', () => {
let xhrs = [];
global.XMLHttpRequest = jest.fn(() => {
let xhr = {
setRequestHeader: jest.fn(),
getAllResponseHeaders: jest.fn().mockReturnValue(''),
open: jest.fn(),
send: jest.fn(),
status: 0,
statusText: '',
responseText: '',
responseURL: '',
onabort: () => {},
abort: jest.fn(() => xhr.onabort())
};
xhrs.push(xhr);
return xhr;
});

const controller = new AbortController();
const p1 = fetch('/foo', { signal: controller.signal });
const p2 = fetch('/bar', { signal: controller.signal });

expect(controller.signal.addEventListener).toHaveBeenCalledTimes(2);
expect(controller.signal.addEventListener).toHaveBeenNthCalledWith(1, 'abort', expect.any(Function));
expect(controller.signal.addEventListener).toHaveBeenNthCalledWith(2, 'abort', expect.any(Function));

controller.abort();

expect(p1).rejects.toThrow(/abort/i);
expect(p2).rejects.toThrow(/abort/i);

expect(xhrs[0].abort).toHaveBeenCalledTimes(1);
expect(xhrs[1].abort).toHaveBeenCalledTimes(1);

return Promise.all([p1.catch(() => {}), p2.catch(() => {})]);
});
});
});