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

Provide a way to easily mock fetch and Web platform polyfills #295

Merged
merged 11 commits into from Apr 12, 2019
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -50,11 +50,11 @@
"globalize": "1.4.0",
"immutable": "3.8.2",
"intersection-observer": "0.4.2",
"isomorphic-fetch": "^2.2.1",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cross-fetch might be a better option for this (I haven't used either): https://github.com/lquixada/cross-fetch#why-not-isomorphic-fetch

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, I've updated this to use cross-fetch

"pepjs": "0.4.2",
"resize-observer-polyfill": "1.5.0",
"tslib": "1.8.1",
"web-animations-js": "2.3.1",
"whatwg-fetch": "3.0.0"
"web-animations-js": "2.3.1"
},
"devDependencies": {
"@dojo/loader": "^2.0.0",
Expand Down
25 changes: 22 additions & 3 deletions src/shim/fetch.ts
@@ -1,5 +1,24 @@
import global from './global';
import dojoGlobal from './global';
`!has('build-elide')`;
import 'whatwg-fetch';
import 'isomorphic-fetch';

export default global.fetch.bind(global) as (input: RequestInfo, init?: RequestInit) => Promise<Response>;
import has from '../has/has';

if (typeof global !== 'undefined' && (global as any).fetch && (global as any).fetch !== dojoGlobal.fetch) {
dojoGlobal.fetch = (global as any).fetch;
}

const _fetch = dojoGlobal.fetch.bind(dojoGlobal) as (input: RequestInfo, init?: RequestInit) => Promise<Response>;
let replacement: (input: RequestInfo, init?: RequestInit) => Promise<Response>;

export default function fetch(input: RequestInfo, init?: RequestInit) {
return replacement ? replacement(input, init) : _fetch(input, init);
}

export function replace(fetch: (input: RequestInfo, init?: RequestInit) => Promise<Response>) {
if (has('test')) {
Copy link
Contributor

@samends samends Mar 18, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is has referring to here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

replacement = fetch;
} else {
throw new Error('Replacement functionality is only available in a test environment');
}
}