-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmockFetch.js
83 lines (73 loc) · 2.43 KB
/
mockFetch.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import fetchMock from "fetch-mock/esm/client";
import { Component } from "preact";
class FetchStory extends Component {
componentWillMount() {
this.mock();
}
componentWillUnmount() {
// @ts-ignore
if (fetchMock.__prevProxy === this) {
this.unmock();
}
}
mock() {
// Clear mocks from a previous FetchStory
this.unmock();
const mocks = this.props.mocks;
if (mocks) {
// @ts-ignore
mocks.forEach((mock) => {
fetchMock.mock({
...mock,
response: (url, opts) => {
if (!this.props.silent) {
console.info("fetch", url, opts);
}
let result = {
body: mock.response,
headers: new Headers({
"content-type": "plain/text",
}),
};
if (
mock.response.hasOwnProperty("body") ||
mock.response.hasOwnProperty("status") ||
mock.response.hasOwnProperty("headers")
) {
result = {
...result,
...mock.response,
};
}
return this.props.throttle
? new Promise((resolve) => {
setTimeout(
() => resolve(result),
this.props.throttle
);
})
: result;
},
});
});
// Allow unmocked requests to fall through
fetchMock.catch((...args) =>
// @ts-ignore
fetchMock.realFetch.apply(window, args)
);
// @ts-ignore
fetchMock.__prevProxy = this;
}
}
unmock() {
if (typeof fetchMock.restore === "function") {
fetchMock.restore();
// @ts-ignore
delete fetchMock.__prevProxy;
}
}
render() {
return this.props.children;
}
}
export default FetchStory;