-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
RelayModernMockEnvironment.js
584 lines (536 loc) · 19.2 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall relay
*/
'use strict';
/* global jest */
import type {
CacheConfig,
ConcreteRequest,
EnvironmentConfig,
GraphQLSingularResponse,
GraphQLTaggedNode,
IEnvironment,
OperationDescriptor,
RequestParameters,
Variables,
} from 'relay-runtime';
import type {Sink} from 'relay-runtime/network/RelayObservable';
const areEqual = require('areEqual');
const invariant = require('invariant');
const {
Environment,
Network,
Observable,
QueryResponseCache,
RecordSource,
Store,
createOperationDescriptor,
getRequest,
} = require('relay-runtime');
type PendingRequest = {
+request: RequestParameters,
+variables: Variables,
+cacheConfig: CacheConfig,
+sink: Sink<GraphQLSingularResponse>,
};
const MAX_SIZE = 10;
const MAX_TTL = 5 * 60 * 1000; // 5 min
function mockInstanceMethod(object: $FlowFixMe, key: string) {
object[key] = jest.fn(object[key].bind(object));
}
function mockDisposableMethod(object: $FlowFixMe, key: string) {
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: $FlowFixMe, key: string) {
const fn = object[key].bind(object);
const subscriptions = [];
object[key] = jest.fn((...args) =>
fn(...args).do({
start: subscription => {
subscriptions.push(subscription);
},
}),
);
object[key].mock.subscriptions = subscriptions;
const mockClear = object[key].mockClear.bind(object[key]);
object[key].mockClear = () => {
mockClear();
object[key].mock.subscriptions = [];
};
}
type OperationMockResolver = (
operation: OperationDescriptor,
) => ?GraphQLSingularResponse | ?Error;
type MockFunctions = {
+clearCache: () => void,
+cachePayload: (
request: ConcreteRequest | OperationDescriptor,
variables: Variables,
payload: GraphQLSingularResponse,
) => void,
+isLoading: (
request: ConcreteRequest | OperationDescriptor,
variables: Variables,
cacheConfig?: CacheConfig,
) => boolean,
+reject: (
request: ConcreteRequest | OperationDescriptor,
error: Error | string,
) => void,
+nextValue: (
request: ConcreteRequest | OperationDescriptor,
payload: GraphQLSingularResponse,
) => void,
+complete: (request: ConcreteRequest | OperationDescriptor) => void,
+resolve: (
request: ConcreteRequest | OperationDescriptor,
payload: $ReadOnlyArray<GraphQLSingularResponse> | GraphQLSingularResponse,
) => void,
+getAllOperations: () => $ReadOnlyArray<OperationDescriptor>,
+findOperation: (
findFn: (operation: OperationDescriptor) => boolean,
) => OperationDescriptor,
+queuePendingOperation: (
query: GraphQLTaggedNode,
variables: Variables,
) => void,
+getMostRecentOperation: () => OperationDescriptor,
+resolveMostRecentOperation: (
payload:
| GraphQLSingularResponse
| ((operation: OperationDescriptor) => GraphQLSingularResponse),
) => void,
+rejectMostRecentOperation: (
error: Error | ((operation: OperationDescriptor) => Error),
) => void,
+queueOperationResolver: (resolver: OperationMockResolver) => void,
};
interface MockEnvironment {
+mock: MockFunctions;
+mockClear: () => void;
}
export interface RelayMockEnvironment extends MockEnvironment, IEnvironment {}
/**
* 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>`:
*
* - `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.
* - `nextValue(...) - will add payload to the processing, but won't complete
* the request ()
* - getAllOperations() - every time there is an operation created by
* the Relay Component (query, mutation, subscription) this operation will be
* added to the internal list on the Mock Environment. This method will return
* an array of all pending operations in the order they occurred.
* - findOperation(findFn) - should find operation if findFn(...) return `true`
* for it. Otherwise, it will throw.
* - getMostRecentOperation(...) - should return the most recent operation
* generated by Relay Component.
* - resolveMostRecentOperation(...) - is accepting `GraphQLSingularResponse` or a
* callback function that will receive `operation` and should return
* `GraphQLSingularResponse`
* - rejectMostRecentOperation(...) - should reject the most recent operation
* with a specific error
*/
function createMockEnvironment(
config?: Partial<EnvironmentConfig>,
): RelayMockEnvironment {
const store = config?.store ?? new Store(new RecordSource());
const cache = new QueryResponseCache({
size: MAX_SIZE,
ttl: MAX_TTL,
});
let pendingRequests: $ReadOnlyArray<PendingRequest> = [];
let pendingOperations: $ReadOnlyArray<OperationDescriptor> = [];
const queuePendingOperation = (
query: GraphQLTaggedNode,
variables: Variables,
): void => {
const operationDescriptor = createOperationDescriptor(
getRequest(query),
variables,
);
pendingOperations = pendingOperations.concat([operationDescriptor]);
};
let resolversQueue: $ReadOnlyArray<OperationMockResolver> = [];
const queueOperationResolver = (resolver: OperationMockResolver): void => {
resolversQueue = resolversQueue.concat([resolver]);
};
// Mock the network layer
const execute = (
request: RequestParameters,
variables: Variables,
cacheConfig: CacheConfig,
) => {
const {id, text} = request;
const cacheID = id ?? text;
let cachedPayload = null;
if (
(cacheConfig?.force == null || cacheConfig?.force === false) &&
cacheID != null
) {
cachedPayload = cache.get(cacheID, variables);
}
if (cachedPayload !== null) {
// $FlowFixMe[incompatible-call]
return Observable.from<GraphQLSingularResponse>(cachedPayload);
}
const currentOperation = pendingOperations.find(
op =>
op.request.node.params === request &&
areEqual(op.request.variables, variables),
);
// Handle network responses added by
if (currentOperation != null && resolversQueue.length > 0) {
const currentResolver = resolversQueue[0];
const result = currentResolver(currentOperation);
if (result != null) {
resolversQueue = resolversQueue.filter(res => res !== currentResolver);
pendingOperations = pendingOperations.filter(
op => op !== currentOperation,
);
if (result instanceof Error) {
return Observable.create<GraphQLSingularResponse>(sink => {
sink.error(result);
});
} else {
return Observable.from<GraphQLSingularResponse>(result);
}
}
}
return Observable.create<GraphQLSingularResponse>(sink => {
const nextRequest = {request, variables, cacheConfig, sink};
pendingRequests = pendingRequests.concat([nextRequest]);
return () => {
pendingRequests = pendingRequests.filter(
pending => !areEqual(pending, nextRequest),
);
pendingOperations = pendingOperations.filter(
op => op !== currentOperation,
);
};
});
};
function getConcreteRequest(
input: ConcreteRequest | OperationDescriptor,
): ConcreteRequest {
if (input.kind === 'Request') {
const request: ConcreteRequest = (input: $FlowFixMe);
return request;
} else {
const operationDescriptor: OperationDescriptor = (input: $FlowFixMe);
invariant(
pendingOperations.includes(operationDescriptor),
'RelayModernMockEnvironment: Operation "%s" was not found in the list of pending operations',
operationDescriptor.request.node.operation.name,
);
return operationDescriptor.request.node;
}
}
// The same request may be made by multiple query renderers
function getRequests(
input: ConcreteRequest | OperationDescriptor,
): $ReadOnlyArray<PendingRequest> {
let concreteRequest: ConcreteRequest;
let operationDescriptor: OperationDescriptor;
if (input.kind === 'Request') {
concreteRequest = (input: $FlowFixMe);
} else {
operationDescriptor = (input: $FlowFixMe);
concreteRequest = operationDescriptor.request.node;
}
const foundRequests = pendingRequests.filter(pending => {
if (!areEqual(pending.request, concreteRequest.params)) {
return false;
}
if (operationDescriptor) {
// If we handling `OperationDescriptor` we also need to check variables
// and return only pending request with equal variables
return areEqual(
operationDescriptor.request.variables,
pending.variables,
);
} else {
// In the case we received `ConcreteRequest` as input we will return
// all pending request, even if they have different variables
return true;
}
});
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.',
concreteRequest.params.name,
);
});
return foundRequests;
}
function ensureValidPayload(payload: GraphQLSingularResponse) {
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: ConcreteRequest | OperationDescriptor,
variables: Variables,
payload: GraphQLSingularResponse,
): void => {
const {id, text} = getConcreteRequest(request).params;
const cacheID = id ?? text;
invariant(cacheID != null, 'CacheID should not be null');
cache.set(cacheID, variables, payload);
};
const clearCache = (): void => {
cache.clear();
};
// Helper to determine if a given query/variables pair is pending
const isLoading = (
request: ConcreteRequest | OperationDescriptor,
variables: Variables,
cacheConfig?: CacheConfig,
): boolean => {
return pendingRequests.some(
pending =>
areEqual(pending.request, getConcreteRequest(request).params) &&
areEqual(pending.variables, variables) &&
areEqual(pending.cacheConfig, cacheConfig ?? {}),
);
};
// Helpers to reject or resolve the payload for an individual request.
const reject = (
request: ConcreteRequest | OperationDescriptor,
error: Error | string,
): void => {
const rejectError = typeof error === 'string' ? new Error(error) : error;
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
invariant(sink !== null, 'Sink should be defined.');
sink.error(rejectError);
});
};
const nextValue = (
request: ConcreteRequest | OperationDescriptor,
payload: GraphQLSingularResponse,
): void => {
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
invariant(sink !== null, 'Sink should be defined.');
sink.next(ensureValidPayload(payload));
});
};
const complete = (request: ConcreteRequest | OperationDescriptor): void => {
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
invariant(sink !== null, 'Sink should be defined.');
sink.complete();
});
};
const resolve = (
request: ConcreteRequest | OperationDescriptor,
response: $ReadOnlyArray<GraphQLSingularResponse> | GraphQLSingularResponse,
): void => {
getRequests(request).forEach(foundRequest => {
const {sink} = foundRequest;
invariant(sink !== null, 'Sink should be defined.');
const payloads = Array.isArray(response) ? response : [response];
payloads.forEach(payload => {
sink.next(ensureValidPayload(payload));
});
sink.complete();
});
};
const getMostRecentOperation = (): OperationDescriptor => {
const mostRecentOperation = pendingOperations[pendingOperations.length - 1];
invariant(
mostRecentOperation != null,
'RelayModernMockEnvironment: There are no pending operations in the list',
);
return mostRecentOperation;
};
const findOperation = (
findFn: (operation: OperationDescriptor) => boolean,
): OperationDescriptor => {
const pendingOperation = pendingOperations.find(findFn);
invariant(
pendingOperation != null,
'RelayModernMockEnvironment: Operation was not found in the list of pending operations',
);
return pendingOperation;
};
// $FlowExpectedError[prop-missing]
const environment: RelayMockEnvironment = new Environment({
configName: 'RelayModernMockEnvironment',
network: Network.create(execute, execute),
store,
...config,
});
const createExecuteProxy = (
env: IEnvironment,
fn: // $FlowFixMe[method-unbinding] added when improving typing for this parameters
| IEnvironment['execute']
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
| IEnvironment['executeSubscription']
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
| IEnvironment['executeWithSource']
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
| IEnvironment['executeMutation'],
) => {
return (...argumentsList: $FlowFixMe) => {
const [{operation}] = argumentsList;
pendingOperations = pendingOperations.concat([operation]);
return fn.apply(env, argumentsList);
};
};
// $FlowExpectedError[cannot-write]
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.execute = createExecuteProxy(environment, environment.execute);
// $FlowExpectedError[cannot-write]
environment.executeSubscription = createExecuteProxy(
environment,
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.executeSubscription,
);
// $FlowExpectedError[cannot-write]
environment.executeWithSource = createExecuteProxy(
environment,
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.executeWithSource,
);
// $FlowExpectedError[cannot-write]
environment.executeMutation = createExecuteProxy(
environment,
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.executeMutation,
);
// $FlowFixMe[incompatible-type]
if (global?.process?.env?.NODE_ENV === 'test') {
// 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, 'executeSubscription');
mockObservableMethod(environment, 'executeWithSource');
mockObservableMethod(environment, 'executeMutation');
mockInstanceMethod(store, 'getSource');
mockInstanceMethod(store, 'lookup');
mockInstanceMethod(store, 'notify');
mockInstanceMethod(store, 'publish');
mockDisposableMethod(store, 'retain');
mockDisposableMethod(store, 'subscribe');
}
const mock: MockFunctions = {
cachePayload,
clearCache,
isLoading,
reject,
resolve,
nextValue,
complete,
getMostRecentOperation,
resolveMostRecentOperation(payload): void {
const operation = getMostRecentOperation();
const data = typeof payload === 'function' ? payload(operation) : payload;
return resolve(operation, data);
},
rejectMostRecentOperation(error): void {
const operation = getMostRecentOperation();
const rejector = typeof error === 'function' ? error(operation) : error;
return reject(operation, rejector);
},
findOperation,
queuePendingOperation,
getAllOperations() {
return pendingOperations;
},
queueOperationResolver,
};
// $FlowExpectedError[cannot-write]
environment.mock = mock;
// $FlowExpectedError[cannot-write]
environment.mockClear = () => {
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.applyUpdate.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.commitPayload.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.getStore.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.lookup.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.check.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.subscribe.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.retain.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.execute.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.executeMutation.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
environment.executeSubscription.mockClear();
// $FlowExpectedError[prop-missing]
store.getSource().clear?.();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.getSource.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.lookup.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.notify.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.publish.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.retain.mockClear();
// $FlowFixMe[method-unbinding] added when improving typing for this parameters
store.subscribe.mockClear();
cache.clear();
pendingOperations = [];
pendingRequests = [];
};
return environment;
}
module.exports = {createMockEnvironment};