Skip to content

Commit 974ef39

Browse files
committed
Fix illegal invocation errors
Fixes #46
1 parent 1aff9c5 commit 974ef39

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export default typeof fetch=='function' ? fetch : function(url, options) {
1+
export default typeof fetch == 'function' && typeof window != 'undefined' ? fetch.bind(window) : function(url, options) {
22
options = options || {};
33
return new Promise( (resolve, reject) => {
44
let request = new XMLHttpRequest();

test/index.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,31 @@ import fetch from '../src';
22
import chai, { expect } from 'chai';
33
import { spy, stub } from 'sinon';
44
import sinonChai from 'sinon-chai';
5-
chai.use(sinonChai);
5+
import { transformFileSync } from 'babel-core';
6+
import vm from 'vm';
67

8+
chai.use(sinonChai);
79

810
describe('unfetch', () => {
911
it('should be a function', () => {
1012
expect(fetch).to.be.a('function');
1113
});
1214

15+
// Prevents illegal invocation errors
16+
// See https://github.com/developit/unfetch/issues/46
17+
it('should bind the native fetch on window', () => {
18+
const filename = require.resolve('../src');
19+
const sandbox = {
20+
window: {},
21+
fetch() { return this },
22+
exports: {}
23+
};
24+
25+
vm.runInNewContext(transformFileSync(filename).code, sandbox, filename);
26+
27+
expect(sandbox.exports.default()).to.equal(sandbox.window);
28+
});
29+
1330
describe('fetch()', () => {
1431
it('sanity test', () => {
1532
let xhr = {

0 commit comments

Comments
 (0)