generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 174
/
fetch.js
29 lines (27 loc) · 835 Bytes
/
fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sinon from 'sinon';
const { fetch: originalFetch } = window;
export async function mockFetch(...stubs) {
const mocks = await Promise.all(stubs.map((stub) => stub(originalFetch)));
mocks.forEach((mock) => {
mock.count = 0;
});
const stub = sinon.stub().callsFake(async (...args) => {
const { href, pathname, searchParams } = new URL(
String(args[0]),
window.location,
);
let found = false;
for await (const mock of mocks) {
found = await mock({ href, pathname, searchParams });
if (found === false) continue;
mock.count++;
break;
}
if (found === false) {
return originalFetch(...args);
}
return found;
});
window.fetch = stub;
return mocks;
}