UNPKG

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