1 |
|
2 | import HTTP from './http';
|
3 |
|
4 | const authMock = {
|
5 | requestToken: async () => 'mock token',
|
6 | shouldRefreshToken: () => false,
|
7 | forceTokenUpdate: async () => {}
|
8 | };
|
9 |
|
10 | export default class HTTPMock extends HTTP {
|
11 | constructor() {
|
12 | super(authMock);
|
13 |
|
14 | this.defaultResponse = null;
|
15 | this.requests = [];
|
16 | this.responsesByUrlMap = new Map();
|
17 | }
|
18 |
|
19 | async _fetch(url, params) {
|
20 | this.requests = [...this.requests, {
|
21 | url,
|
22 | params: {
|
23 | ...params,
|
24 | body: params.body ? JSON.parse(params.body) : params.body
|
25 | }
|
26 | }];
|
27 |
|
28 | return {
|
29 | status: 200,
|
30 | headers: new Headers({'content-type': 'application/json'}),
|
31 | json: async () => (this._getResponseForUrl(url) || this.defaultResponse)
|
32 | };
|
33 | }
|
34 |
|
35 | respondDefault(response) {
|
36 | this.defaultResponse = response;
|
37 | }
|
38 |
|
39 | respondForUrl(url, response) {
|
40 | this.responsesByUrlMap.set(url, response);
|
41 | }
|
42 |
|
43 | _getResponseForUrl(urlToMatch) {
|
44 | const urls = this.responsesByUrlMap.keys();
|
45 |
|
46 | for (const url of urls) {
|
47 | if (url === urlToMatch) {
|
48 | return this.responsesByUrlMap.get(url);
|
49 | }
|
50 |
|
51 | if (url.test && url.test(urlToMatch)) {
|
52 | return this.responsesByUrlMap.get(url);
|
53 | }
|
54 | }
|
55 |
|
56 | return null;
|
57 | }
|
58 |
|
59 | getRequestsByUrlPart(url) {
|
60 | return this.requests.filter(it => it.url.indexOf(url) !== -1);
|
61 | }
|
62 | }
|