-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
RelayModernMockEnvironment.js
280 lines (248 loc) · 7.55 KB
/
RelayModernMockEnvironment.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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const RelayModernTestUtils = require('RelayModernTestUtils');
const RelayTestSchema = require('RelayTestSchema');
const areEqual = require('areEqual');
const invariant = require('invariant');
const MAX_SIZE = 10;
const MAX_TTL = 5 * 60 * 1000; // 5 min
function mockInstanceMethod(object, key) {
object[key] = jest.fn(object[key].bind(object));
}
function mockDisposableMethod(object, key) {
const fn = object[key].bind(object);
object[key] = jest.fn((...args) => {
const disposable = fn(...args);
const dispose = jest.fn(() => disposable.dispose());
object[key].mock.dispose = dispose;
return {dispose};
});
const mockClear = object[key].mockClear.bind(object[key]);
object[key].mockClear = () => {
mockClear();
object[key].mock.dispose = null;
};
}
function mockObservableMethod(object, key) {
const fn = object[key].bind(object);
object[key] = jest.fn((...args) =>
fn(...args).do({
start: subscription => {
object[key].mock.subscriptions.push(subscription);
},
}),
);
object[key].mock.subscriptions = [];
const mockClear = object[key].mockClear.bind(object[key]);
object[key].mockClear = () => {
mockClear();
object[key].mock.subscriptions = [];
};
}
/**
* Creates an instance of the `Environment` interface defined in
* RelayStoreTypes with a mocked network layer.
*
* Usage:
*
* ```
* const environment = RelayModernMockEnvironment.createMockEnvironment();
* ```
*
* Mock API:
*
* Helpers are available as `environment.mock.<helper>`:
*
* - `compile(text: string): {[queryName]: Query}`: Create a query.
* - `isLoading(query, variables): boolean`: Determine whether the given query
* is currently being loaded (not yet rejected/resolved).
* - `reject(query, error: Error): void`: Reject a query that has been fetched
* by the environment.
* - `resolve(query, payload: PayloadData): void`: Resolve a query that has been
* fetched by the environment.
*/
function createMockEnvironment(options: {
schema?: ?GraphQLSchema,
handlerProvider?: ?HandlerProvider,
}) {
const {
RecordSource,
Store,
QueryResponseCache,
Observable,
Environment,
Network,
} = require('relay-runtime');
const schema = options && options.schema;
const handlerProvider = options && options.handlerProvider;
const source = new RecordSource();
const store = new Store(source);
const cache = new QueryResponseCache({
size: MAX_SIZE,
ttl: MAX_TTL,
});
// Mock the network layer
let pendingRequests = [];
const execute = (request, variables, cacheConfig) => {
const {id, text} = request;
const cacheID = id || text;
let cachedPayload = null;
if (!cacheConfig || !cacheConfig.force) {
cachedPayload = cache.get(cacheID, variables);
}
if (cachedPayload !== null) {
return Observable.from(cachedPayload);
}
const nextRequest = {request, variables, cacheConfig};
pendingRequests = pendingRequests.concat([nextRequest]);
return Observable.create(sink => {
nextRequest.sink = sink;
return () => {
pendingRequests = pendingRequests.filter(
pending => pending !== nextRequest,
);
};
});
};
// The same request may be made by multiple query renderers
function getRequests(request) {
const foundRequests = pendingRequests.filter(
pending => pending.request === request,
);
invariant(
foundRequests.length,
'MockEnvironment: Cannot respond to request, it has not been requested yet.',
);
foundRequests.forEach(foundRequest => {
invariant(
foundRequest.sink,
'MockEnvironment: Cannot respond to `%s`, it has not been requested yet.',
foundRequest.name,
);
});
return foundRequests;
}
function ensureValidPayload(payload) {
invariant(
typeof payload === 'object' &&
payload !== null &&
payload.hasOwnProperty('data'),
'MockEnvironment(): Expected payload to be an object with a `data` key.',
);
return payload;
}
const cachePayload = (request, variables, payload) => {
const {id, text} = request;
const cacheID = id || text;
cache.set(cacheID, variables, payload);
};
const clearCache = () => {
cache.clear();
};
if (!schema) {
global.__RELAYOSS__ = true;
}
// Helper to compile a query with the given schema (or the test schema by
// default).
const compile = text => {
return RelayModernTestUtils.generateAndCompile(
text,
schema || RelayTestSchema,
);
};
// Helper to determine if a given query/variables pair is pending
const isLoading = (request, variables, cacheConfig) => {
return pendingRequests.some(
pending =>
pending.request === request &&
areEqual(pending.variables, variables) &&
areEqual(pending.cacheConfig, cacheConfig || {}),
);
};
// Helpers to reject or resolve the payload for an individual request.
const reject = (request, error) => {
if (typeof error === 'string') {
error = new Error(error);
}
getRequests(request).forEach(foundRequest =>
foundRequest.sink.error(error),
);
};
const nextValue = (request, payload) => {
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
sink.next(ensureValidPayload(payload));
});
};
const complete = request => {
getRequests(request).forEach(foundRequest => foundRequest.sink.complete());
};
const resolve = (request, payload) => {
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
sink.next(ensureValidPayload(payload));
sink.complete();
});
};
// Mock instance
const environment = new Environment({
configName: 'RelayModernMockEnvironment',
handlerProvider,
network: Network.create(execute, execute),
store,
});
// Mock all the functions with their original behavior
mockDisposableMethod(environment, 'applyUpdate');
mockInstanceMethod(environment, 'commitPayload');
mockInstanceMethod(environment, 'getStore');
mockInstanceMethod(environment, 'lookup');
mockInstanceMethod(environment, 'check');
mockDisposableMethod(environment, 'subscribe');
mockDisposableMethod(environment, 'retain');
mockObservableMethod(environment, 'execute');
mockObservableMethod(environment, 'executeMutation');
mockInstanceMethod(store, 'getSource');
mockInstanceMethod(store, 'lookup');
mockInstanceMethod(store, 'notify');
mockInstanceMethod(store, 'publish');
mockDisposableMethod(store, 'retain');
mockDisposableMethod(store, 'subscribe');
environment.mock = {
cachePayload,
clearCache,
compile,
isLoading,
reject,
resolve,
nextValue,
complete,
};
environment.mockClear = () => {
environment.applyUpdate.mockClear();
environment.commitPayload.mockClear();
environment.getStore.mockClear();
environment.lookup.mockClear();
environment.check.mockClear();
environment.subscribe.mockClear();
environment.retain.mockClear();
environment.execute.mockClear();
environment.executeMutation.mockClear();
store.getSource.mockClear();
store.lookup.mockClear();
store.notify.mockClear();
store.publish.mockClear();
store.retain.mockClear();
store.subscribe.mockClear();
cache.clear();
pendingRequests = [];
};
return environment;
}
module.exports = {createMockEnvironment};