-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (34 loc) · 978 Bytes
/
index.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
30
31
32
33
34
35
36
37
38
export default class ChaosRequest {
constructor(shouldChangeResponse, getResponse) {
this.shouldChangeResponse = typeof shouldChangeResponse === 'function' ? shouldChangeResponse : function() {
return true;
};
this.getResponse = typeof getResponse === 'function' ? getResponse : function() {
return {
body: JSON.stringify({}),
init: {
status: 200,
statusText: 'OK',
headers: {
'Content-type': 'application/json',
},
},
};
};
}
mock() {
this.fetch = window.fetch;
window.fetch = (...args) => {
if (this.shouldChangeResponse(args)) {
return new Promise((resolve) => {
Promise.resolve(this.getResponse(args, this.fetch))
.then(response => resolve(new Response(response.body, response.init)));
});
}
return this.fetch.apply(null, args);
}
}
restore() {
window.fetch = this.fetch;
}
};