UNPKG

22.4 kBJavaScriptView Raw
1/**
2 * Relay v1.7.0
3 *
4 * Copyright (c) 2013-present, Facebook, Inc.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9var RelayTestUtils =
10/******/ (function(modules) { // webpackBootstrap
11/******/ // The module cache
12/******/ var installedModules = {};
13
14/******/ // The require function
15/******/ function __webpack_require__(moduleId) {
16
17/******/ // Check if module is in cache
18/******/ if(installedModules[moduleId])
19/******/ return installedModules[moduleId].exports;
20
21/******/ // Create a new module (and put it into the cache)
22/******/ var module = installedModules[moduleId] = {
23/******/ exports: {},
24/******/ id: moduleId,
25/******/ loaded: false
26/******/ };
27
28/******/ // Execute the module function
29/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
30
31/******/ // Flag the module as loaded
32/******/ module.loaded = true;
33
34/******/ // Return the exports of the module
35/******/ return module.exports;
36/******/ }
37
38
39/******/ // expose the modules object (__webpack_modules__)
40/******/ __webpack_require__.m = modules;
41
42/******/ // expose the module cache
43/******/ __webpack_require__.c = installedModules;
44
45/******/ // __webpack_public_path__
46/******/ __webpack_require__.p = "";
47
48/******/ // Load entry module and return exports
49/******/ return __webpack_require__(0);
50/******/ })
51/************************************************************************/
52/******/ ([
53/* 0 */
54/***/ (function(module, exports, __webpack_require__) {
55
56 /**
57 * Copyright (c) 2013-present, Facebook, Inc.
58 *
59 * This source code is licensed under the MIT license found in the
60 * LICENSE file in the root directory of this source tree.
61 *
62 *
63 * @format
64 */
65
66 'use strict';
67
68 /**
69 * The public interface to Relay Test Utils.
70 */
71 module.exports = {
72 MockEnvironment: __webpack_require__(9),
73 testSchemaPath: __webpack_require__(5)
74 };
75
76/***/ }),
77/* 1 */
78/***/ (function(module, exports) {
79
80 module.exports = relay-compiler;
81
82/***/ }),
83/* 2 */
84/***/ (function(module, exports) {
85
86 module.exports = fbjs/lib/invariant;
87
88/***/ }),
89/* 3 */
90/***/ (function(module, exports) {
91
92 module.exports = graphql;
93
94/***/ }),
95/* 4 */
96/***/ (function(module, exports, __webpack_require__) {
97
98 /**
99 * Copyright (c) 2013-present, Facebook, Inc.
100 *
101 * This source code is licensed under the MIT license found in the
102 * LICENSE file in the root directory of this source tree.
103 *
104 * strict
105 * @format
106 */
107
108 'use strict';
109
110 module.exports = __webpack_require__(3).buildASTSchema(__webpack_require__(3).parse(__webpack_require__(7).readFileSync(__webpack_require__(5), 'utf8'), { assumeValid: true }));
111
112/***/ }),
113/* 5 */
114/***/ (function(module, exports, __webpack_require__) {
115
116 /* WEBPACK VAR INJECTION */(function(__dirname) {/**
117 * Copyright (c) 2013-present, Facebook, Inc.
118 *
119 * This source code is licensed under the MIT license found in the
120 * LICENSE file in the root directory of this source tree.
121 *
122 * strict
123 * @format
124 */
125
126 'use strict';
127
128 module.exports = __webpack_require__(8).join(__dirname, 'testschema.graphql');
129 /* WEBPACK VAR INJECTION */}.call(exports, "/"))
130
131/***/ }),
132/* 6 */
133/***/ (function(module, exports) {
134
135 module.exports = fbjs/lib/areEqual;
136
137/***/ }),
138/* 7 */
139/***/ (function(module, exports) {
140
141 module.exports = fs;
142
143/***/ }),
144/* 8 */
145/***/ (function(module, exports) {
146
147 module.exports = path;
148
149/***/ }),
150/* 9 */
151/***/ (function(module, exports, __webpack_require__) {
152
153 /**
154 * Copyright (c) 2013-present, Facebook, Inc.
155 *
156 * This source code is licensed under the MIT license found in the
157 * LICENSE file in the root directory of this source tree.
158 *
159 * @format
160 */
161
162 'use strict';
163
164 var MAX_SIZE = 10;
165 var MAX_TTL = 5 * 60 * 1000; // 5 min
166
167 function mockInstanceMethod(object, key) {
168 object[key] = jest.fn(object[key].bind(object));
169 }
170
171 function mockDisposableMethod(object, key) {
172 var fn = object[key].bind(object);
173 object[key] = jest.fn(function () {
174 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
175 args[_key] = arguments[_key];
176 }
177
178 var disposable = fn.apply(undefined, args);
179 var dispose = jest.fn(function () {
180 return disposable.dispose();
181 });
182 object[key].mock.dispose = dispose;
183 return { dispose: dispose };
184 });
185 var mockClear = object[key].mockClear.bind(object[key]);
186 object[key].mockClear = function () {
187 mockClear();
188 object[key].mock.dispose = null;
189 };
190 }
191
192 function mockObservableMethod(object, key) {
193 var fn = object[key].bind(object);
194 object[key] = jest.fn(function () {
195 for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
196 args[_key2] = arguments[_key2];
197 }
198
199 return fn.apply(undefined, args)['do']({
200 start: function start(subscription) {
201 object[key].mock.subscriptions.push(subscription);
202 }
203 });
204 });
205 object[key].mock.subscriptions = [];
206 var mockClear = object[key].mockClear.bind(object[key]);
207 object[key].mockClear = function () {
208 mockClear();
209 object[key].mock.subscriptions = [];
210 };
211 }
212
213 /**
214 * Creates an instance of the `Environment` interface defined in
215 * RelayStoreTypes with a mocked network layer.
216 *
217 * Usage:
218 *
219 * ```
220 * const environment = RelayModernMockEnvironment.createMockEnvironment();
221 * ```
222 *
223 * Mock API:
224 *
225 * Helpers are available as `environment.mock.<helper>`:
226 *
227 * - `compile(text: string): {[queryName]: Query}`: Create a query.
228 * - `isLoading(query, variables): boolean`: Determine whether the given query
229 * is currently being loaded (not yet rejected/resolved).
230 * - `reject(query, error: Error): void`: Reject a query that has been fetched
231 * by the environment.
232 * - `resolve(query, payload: PayloadData): void`: Resolve a query that has been
233 * fetched by the environment.
234 */
235 function createMockEnvironment(options) {
236 var _require = __webpack_require__(16),
237 RecordSource = _require.RecordSource,
238 Store = _require.Store,
239 QueryResponseCache = _require.QueryResponseCache,
240 Observable = _require.Observable,
241 Environment = _require.Environment,
242 Network = _require.Network;
243
244 var schema = options && options.schema;
245 var handlerProvider = options && options.handlerProvider;
246 var source = new RecordSource();
247 var store = new Store(source);
248 var cache = new QueryResponseCache({
249 size: MAX_SIZE,
250 ttl: MAX_TTL
251 });
252
253 // Mock the network layer
254 var pendingRequests = [];
255 var execute = function execute(request, variables, cacheConfig) {
256 var id = request.id,
257 text = request.text;
258
259 var cacheID = id || text;
260
261 var cachedPayload = null;
262 if (!cacheConfig || !cacheConfig.force) {
263 cachedPayload = cache.get(cacheID, variables);
264 }
265 if (cachedPayload !== null) {
266 return Observable.from(cachedPayload);
267 }
268
269 var nextRequest = { request: request, variables: variables, cacheConfig: cacheConfig };
270 pendingRequests = pendingRequests.concat([nextRequest]);
271
272 return Observable.create(function (sink) {
273 nextRequest.sink = sink;
274 return function () {
275 pendingRequests = pendingRequests.filter(function (pending) {
276 return pending !== nextRequest;
277 });
278 };
279 });
280 };
281
282 function getRequest(request) {
283 var foundRequest = pendingRequests.find(function (pending) {
284 return pending.request === request;
285 });
286 !(foundRequest && foundRequest.sink) ? false ? require('fbjs/lib/invariant')(false, 'MockEnvironment: Cannot respond to `%s`, it has not been requested yet.', request.name) : __webpack_require__(2)(false) : void 0;
287 return foundRequest;
288 }
289
290 function ensureValidPayload(payload) {
291 !(typeof payload === 'object' && payload !== null && payload.hasOwnProperty('data')) ? false ? require('fbjs/lib/invariant')(false, 'MockEnvironment(): Expected payload to be an object with a `data` key.') : __webpack_require__(2)(false) : void 0;
292 return payload;
293 }
294
295 var cachePayload = function cachePayload(request, variables, payload) {
296 var id = request.id,
297 text = request.text;
298
299 var cacheID = id || text;
300 cache.set(cacheID, variables, payload);
301 };
302
303 var clearCache = function clearCache() {
304 cache.clear();
305 };
306
307 if (!schema) {
308 global.__RELAYOSS__ = true;
309 }
310
311 // Helper to compile a query with the given schema (or the test schema by
312 // default).
313 var compile = function compile(text) {
314 return __webpack_require__(10).generateAndCompile(text, schema || __webpack_require__(4));
315 };
316
317 // Helper to determine if a given query/variables pair is pending
318 var isLoading = function isLoading(request, variables, cacheConfig) {
319 return pendingRequests.some(function (pending) {
320 return pending.request === request && __webpack_require__(6)(pending.variables, variables) && __webpack_require__(6)(pending.cacheConfig, cacheConfig || {});
321 });
322 };
323
324 // Helpers to reject or resolve the payload for an individual request.
325 var reject = function reject(request, error) {
326 if (typeof error === 'string') {
327 error = new Error(error);
328 }
329 getRequest(request).sink.error(error);
330 };
331
332 var nextValue = function nextValue(request, payload) {
333 var _getRequest = getRequest(request),
334 sink = _getRequest.sink,
335 variables = _getRequest.variables;
336
337 sink.next({
338 kind: 'data',
339 operation: request.operation,
340 variables: variables,
341 response: ensureValidPayload(payload)
342 });
343 };
344
345 var complete = function complete(request) {
346 getRequest(request).sink.complete();
347 };
348
349 var resolve = function resolve(request, payload) {
350 var _getRequest2 = getRequest(request),
351 sink = _getRequest2.sink,
352 variables = _getRequest2.variables;
353
354 sink.next({
355 kind: 'data',
356 operation: request.operation,
357 variables: variables,
358 response: ensureValidPayload(payload)
359 });
360 sink.complete();
361 };
362
363 // Mock instance
364 var environment = new Environment({
365 configName: 'RelayModernMockEnvironment',
366 handlerProvider: handlerProvider,
367 network: Network.create(execute, execute),
368 store: store
369 });
370 // Mock all the functions with their original behavior
371 mockDisposableMethod(environment, 'applyUpdate');
372 mockInstanceMethod(environment, 'commitPayload');
373 mockInstanceMethod(environment, 'getStore');
374 mockInstanceMethod(environment, 'lookup');
375 mockInstanceMethod(environment, 'check');
376 mockDisposableMethod(environment, 'subscribe');
377 mockDisposableMethod(environment, 'retain');
378 mockObservableMethod(environment, 'execute');
379 mockObservableMethod(environment, 'executeMutation');
380
381 mockInstanceMethod(store, 'getSource');
382 mockInstanceMethod(store, 'lookup');
383 mockInstanceMethod(store, 'notify');
384 mockInstanceMethod(store, 'publish');
385 mockDisposableMethod(store, 'retain');
386 mockDisposableMethod(store, 'subscribe');
387
388 environment.mock = {
389 cachePayload: cachePayload,
390 clearCache: clearCache,
391 compile: compile,
392 isLoading: isLoading,
393 reject: reject,
394 resolve: resolve,
395 nextValue: nextValue,
396 complete: complete
397 };
398
399 environment.mockClear = function () {
400 environment.applyUpdate.mockClear();
401 environment.commitPayload.mockClear();
402 environment.getStore.mockClear();
403 environment.lookup.mockClear();
404 environment.check.mockClear();
405 environment.subscribe.mockClear();
406 environment.retain.mockClear();
407 environment.execute.mockClear();
408 environment.executeMutation.mockClear();
409
410 store.getSource.mockClear();
411 store.lookup.mockClear();
412 store.notify.mockClear();
413 store.publish.mockClear();
414 store.retain.mockClear();
415 store.subscribe.mockClear();
416
417 cache.clear();
418
419 pendingRequests = [];
420 };
421
422 return environment;
423 }
424
425 module.exports = { createMockEnvironment: createMockEnvironment };
426
427/***/ }),
428/* 10 */
429/***/ (function(module, exports, __webpack_require__) {
430
431 /**
432 * Copyright (c) 2013-present, Facebook, Inc.
433 *
434 * This source code is licensed under the MIT license found in the
435 * LICENSE file in the root directory of this source tree.
436 *
437 * @format
438 */
439
440 'use strict';
441
442 var _asyncToGenerator2 = __webpack_require__(12);
443
444 var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
445
446 var _defineProperty3 = _interopRequireDefault(__webpack_require__(13));
447
448 let getOutputForFixture = (() => {
449 var _ref3 = (0, _asyncToGenerator3.default)(function* (input, operation) {
450 try {
451 var output = operation(input);
452 return output instanceof Promise ? yield output : output;
453 } catch (e) {
454 return 'THROWN EXCEPTION:\n\n' + e.toString();
455 }
456 });
457
458 return function getOutputForFixture(_x2, _x3) {
459 return _ref3.apply(this, arguments);
460 };
461 })();
462
463 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
464
465 var FIXTURE_TAG = Symbol['for']('FIXTURE_TAG');
466
467 /**
468 * Extend Jest with a custom snapshot serializer to provide additional context
469 * and reduce the amount of escaping that occurs.
470 */
471 expect.addSnapshotSerializer({
472 print: function print(value) {
473 return Object.keys(value).map(function (key) {
474 return '~~~~~~~~~~ ' + key.toUpperCase() + ' ~~~~~~~~~~\n' + value[key];
475 }).join('\n');
476 },
477 test: function test(value) {
478 return value && value[FIXTURE_TAG] === true;
479 }
480 });
481
482 /**
483 * Utilities (custom matchers etc) for Relay "static" tests.
484 */
485 var RelayModernTestUtils = {
486 matchers: {
487 toBeDeeplyFrozen: function toBeDeeplyFrozen(actual) {
488 var _require = __webpack_require__(15),
489 isCollection = _require.isCollection,
490 forEach = _require.forEach;
491
492 function check(value) {
493 expect(Object.isFrozen(value)).toBe(true);
494 if (isCollection(value)) {
495 forEach(value, check);
496 } else if (typeof value === 'object' && value !== null) {
497 for (var _key in value) {
498 check(value[_key]);
499 }
500 }
501 }
502 check(actual);
503 return {
504 pass: true
505 };
506 },
507 toFailInvariant: function toFailInvariant(actual, expected) {
508 expect(actual).toThrowError(expected);
509 return {
510 pass: true
511 };
512 },
513 toWarn: function toWarn(actual, expected) {
514 var negative = this.isNot;
515
516 function formatItem(item) {
517 return item instanceof RegExp ? item.toString() : JSON.stringify(item);
518 }
519
520 function formatArray(array) {
521 return '[' + array.map(formatItem).join(', ') + ']';
522 }
523
524 function formatExpected(args) {
525 return formatArray([false].concat(args));
526 }
527
528 function formatActual(calls) {
529 if (calls.length) {
530 return calls.map(function (args) {
531 return formatArray([!!args[0]].concat(args.slice(1)));
532 }).join(', ');
533 } else {
534 return '[]';
535 }
536 }
537
538 var warning = __webpack_require__(14);
539 if (!warning.mock) {
540 throw new Error("toWarn(): Requires `jest.mock('warning')`.");
541 }
542
543 var callsCount = warning.mock.calls.length;
544 actual();
545 var calls = warning.mock.calls.slice(callsCount);
546
547 // Simple case: no explicit expectation.
548 if (!expected) {
549 var warned = calls.filter(function (args) {
550 return !args[0];
551 }).length;
552 return {
553 pass: !!warned,
554 message: function message() {
555 return 'Expected ' + (negative ? 'not ' : '') + 'to warn but ' + '`warning` received the following calls: ' + (formatActual(calls) + '.');
556 }
557 };
558 }
559
560 // Custom case: explicit expectation.
561 if (!Array.isArray(expected)) {
562 expected = [expected];
563 }
564 var call = calls.find(function (args) {
565 return args.length === expected.length + 1 && args.every(function (arg, index) {
566 if (!index) {
567 return !arg;
568 }
569 var other = expected[index - 1];
570 return other instanceof RegExp ? other.test(arg) : arg === other;
571 });
572 });
573
574 return {
575 pass: !!call,
576 message: function message() {
577 return 'Expected ' + (negative ? 'not ' : '') + 'to warn: ' + (formatExpected(expected) + ' but ') + '`warning` received the following calls: ' + (formatActual(calls) + '.');
578 }
579 };
580 },
581 toThrowTypeError: function toThrowTypeError(fn) {
582 var pass = false;
583 try {
584 fn();
585 } catch (e) {
586 pass = e instanceof TypeError;
587 }
588 return {
589 pass: pass,
590 message: function message() {
591 return 'Expected function to throw a TypeError.';
592 }
593 };
594 }
595 },
596
597 /**
598 * Parses GraphQL text, applies the selected transforms only (or none if
599 * transforms is not specified), and returns a mapping of definition name to
600 * its basic generated representation.
601 */
602 generateWithTransforms: function generateWithTransforms(text, transforms) {
603 var RelayTestSchema = __webpack_require__(4);
604 return generate(text, RelayTestSchema, {
605 commonTransforms: transforms || [],
606 fragmentTransforms: [],
607 queryTransforms: [],
608 codegenTransforms: [],
609 printTransforms: []
610 });
611 },
612
613
614 /**
615 * Compiles the given GraphQL text using the standard set of transforms (as
616 * defined in RelayCompiler) and returns a mapping of definition name to
617 * its full runtime representation.
618 */
619 generateAndCompile: function generateAndCompile(text, schema) {
620 var RelayCompilerPublic = __webpack_require__(1);
621 var IRTransforms = RelayCompilerPublic.IRTransforms;
622
623 var RelayTestSchema = __webpack_require__(4);
624 return generate(text, schema || RelayTestSchema, IRTransforms);
625 },
626
627
628 /**
629 * Generates a set of jest snapshot tests that compare the output of the
630 * provided `operation` to each of the matching files in the `fixturesPath`.
631 */
632 generateTestsFromFixtures: function generateTestsFromFixtures(fixturesPath, operation) {
633 var fs = __webpack_require__(7);
634 var path = __webpack_require__(8);
635 var tests = fs.readdirSync(fixturesPath).map((() => {
636 var _ref = (0, _asyncToGenerator3.default)(function* (file) {
637 var input = fs.readFileSync(path.join(fixturesPath, file), 'utf8');
638 var output = yield getOutputForFixture(input, operation);
639 return {
640 file: file,
641 input: input,
642 output: output
643 };
644 });
645
646 return function (_x) {
647 return _ref.apply(this, arguments);
648 };
649 })());
650 !(tests.length > 0) ? false ? require('fbjs/lib/invariant')(false, 'generateTestsFromFixtures: No fixtures found at %s', fixturesPath) : __webpack_require__(2)(false) : void 0;
651 it('matches expected output', (0, _asyncToGenerator3.default)(function* () {
652 var results = yield Promise.all(tests);
653 results.forEach(function (test) {
654 var _expect;
655
656 expect((_expect = {}, (0, _defineProperty3['default'])(_expect, FIXTURE_TAG, true), (0, _defineProperty3['default'])(_expect, 'input', test.input), (0, _defineProperty3['default'])(_expect, 'output', test.output), _expect)).toMatchSnapshot(test.file);
657 });
658 }));
659 },
660
661
662 /**
663 * Returns original component class wrapped by e.g. createFragmentContainer
664 */
665 unwrapContainer: function unwrapContainer(ComponentClass) {
666 // $FlowExpectedError
667 var unwrapped = ComponentClass.__ComponentClass;
668 !(unwrapped != null) ? false ? require('fbjs/lib/invariant')(false, 'Could not find component for %s, is it a Relay container?', ComponentClass.displayName || ComponentClass.name) : __webpack_require__(2)(false) : void 0;
669 return unwrapped;
670 }
671 };
672
673 function generate(text, schema, transforms) {
674 var RelayCompilerPublic = __webpack_require__(1);
675 var compileRelayArtifacts = RelayCompilerPublic.compileRelayArtifacts,
676 GraphQLCompilerContext = RelayCompilerPublic.GraphQLCompilerContext,
677 IRTransforms = RelayCompilerPublic.IRTransforms,
678 transformASTSchema = RelayCompilerPublic.transformASTSchema;
679
680
681 var relaySchema = transformASTSchema(schema, IRTransforms.schemaExtensions);
682 var compilerContext = new GraphQLCompilerContext(schema, relaySchema).addAll(__webpack_require__(11)(relaySchema, text).definitions);
683 var documentMap = {};
684 compileRelayArtifacts(compilerContext, transforms).forEach(function (node) {
685 documentMap[node.name] = node;
686 });
687 return documentMap;
688 }
689
690 module.exports = RelayModernTestUtils;
691
692/***/ }),
693/* 11 */
694/***/ (function(module, exports, __webpack_require__) {
695
696 /**
697 * Copyright (c) 2013-present, Facebook, Inc.
698 *
699 * This source code is licensed under the MIT license found in the
700 * LICENSE file in the root directory of this source tree.
701 *
702 * strict-local
703 * @format
704 */
705
706 'use strict';
707
708 function parseGraphQLText(schema, text) {
709 var ast = __webpack_require__(3).parse(text);
710 // TODO T24511737 figure out if this is dangerous
711 var extendedSchema = __webpack_require__(3).extendSchema(schema, ast, { assumeValid: true });
712 var definitions = __webpack_require__(1).convertASTDocuments(extendedSchema, [ast], [], __webpack_require__(1).Parser.transform.bind(__webpack_require__(1).Parser));
713 return {
714 definitions: definitions,
715 schema: extendedSchema !== schema ? extendedSchema : null
716 };
717 }
718
719 module.exports = parseGraphQLText;
720
721/***/ }),
722/* 12 */
723/***/ (function(module, exports) {
724
725 module.exports = babel-runtime/helpers/asyncToGenerator;
726
727/***/ }),
728/* 13 */
729/***/ (function(module, exports) {
730
731 module.exports = babel-runtime/helpers/defineProperty;
732
733/***/ }),
734/* 14 */
735/***/ (function(module, exports) {
736
737 module.exports = fbjs/lib/warning;
738
739/***/ }),
740/* 15 */
741/***/ (function(module, exports) {
742
743 module.exports = iterall;
744
745/***/ }),
746/* 16 */
747/***/ (function(module, exports) {
748
749 module.exports = relay-runtime;
750
751/***/ })
752/******/ ]);
\No newline at end of file