This repository has been archived by the owner on Apr 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 786
/
Copy pathmockLink.ts
158 lines (141 loc) · 4.43 KB
/
mockLink.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import {
Operation,
GraphQLRequest,
ApolloLink,
FetchResult,
Observable
} from 'apollo-link';
import {
addTypenameToDocument,
removeClientSetsFromDocument,
removeConnectionDirectiveFromDocument,
cloneDeep,
isEqual
} from 'apollo-utilities';
import { print } from 'graphql/language/printer';
import stringify from 'fast-json-stable-stringify';
import { MockedResponse, ResultFunction } from './types';
function requestToKey(request: GraphQLRequest, addTypename: Boolean): string {
const queryString =
request.query &&
print(addTypename ? addTypenameToDocument(request.query) : request.query);
const requestKey = { query: queryString };
return JSON.stringify(requestKey);
}
export class MockLink extends ApolloLink {
public addTypename: Boolean = true;
private mockedResponsesByKey: { [key: string]: MockedResponse[] } = {};
constructor(
mockedResponses: ReadonlyArray<MockedResponse>,
addTypename: Boolean = true
) {
super();
this.addTypename = addTypename;
if (mockedResponses)
mockedResponses.forEach(mockedResponse => {
this.addMockedResponse(mockedResponse);
});
}
public addMockedResponse(mockedResponse: MockedResponse) {
const normalizedMockedResponse = this.normalizeMockedResponse(
mockedResponse
);
const key = requestToKey(
normalizedMockedResponse.request,
this.addTypename
);
let mockedResponses = this.mockedResponsesByKey[key];
if (!mockedResponses) {
mockedResponses = [];
this.mockedResponsesByKey[key] = mockedResponses;
}
mockedResponses.push(normalizedMockedResponse);
}
public request(operation: Operation): Observable<FetchResult> | null {
const key = requestToKey(operation, this.addTypename);
let responseIndex;
const response = (this.mockedResponsesByKey[key] || []).find(
(res, index) => {
const requestVariables = operation.variables || {};
const mockedResponseVariables = res.request.variables || {};
if (
!isEqual(
stringify(requestVariables),
stringify(mockedResponseVariables)
)
) {
return false;
}
responseIndex = index;
return true;
}
);
if (!response || typeof responseIndex === 'undefined') {
throw new Error(
`No more mocked responses for the query: ${print(
operation.query
)}, variables: ${JSON.stringify(operation.variables)}`
);
}
this.mockedResponsesByKey[key].splice(responseIndex, 1);
const { result, error, delay, newData } = response;
if (newData) {
response.result = newData();
this.mockedResponsesByKey[key].push(response);
}
if (!result && !error) {
throw new Error(
`Mocked response should contain either result or error: ${key}`
);
}
return new Observable(observer => {
let timer = setTimeout(
() => {
if (error) {
observer.error(error);
} else {
if (result) {
observer.next(
typeof result === 'function'
? (result as ResultFunction<FetchResult>)()
: result
);
}
observer.complete();
}
},
delay ? delay : 0
);
return () => {
clearTimeout(timer);
};
});
}
private normalizeMockedResponse(
mockedResponse: MockedResponse
): MockedResponse {
const newMockedResponse = cloneDeep(mockedResponse);
newMockedResponse.request.query = removeConnectionDirectiveFromDocument(
newMockedResponse.request.query
);
const query = removeClientSetsFromDocument(newMockedResponse.request.query);
if (query) {
newMockedResponse.request.query = query;
}
return newMockedResponse;
}
}
// Pass in multiple mocked responses, so that you can test flows that end up
// making multiple queries to the server.
// NOTE: The last arg can optionally be an `addTypename` arg.
export function mockSingleLink(...mockedResponses: Array<any>): ApolloLink {
// To pull off the potential typename. If this isn't a boolean, we'll just
// set it true later.
let maybeTypename = mockedResponses[mockedResponses.length - 1];
let mocks = mockedResponses.slice(0, mockedResponses.length - 1);
if (typeof maybeTypename !== 'boolean') {
mocks = mockedResponses;
maybeTypename = true;
}
return new MockLink(mocks, maybeTypename);
}