Debian Codegraph @

closure-library/closure/goog/promise/promise_test.js

raw
1 // Copyright 2013 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 goog.provide('goog.PromiseTest');
16
17 goog.require('goog.Promise');
18 goog.require('goog.Thenable');
19 goog.require('goog.Timer');
20 goog.require('goog.functions');
21 goog.require('goog.testing.MockClock');
22 goog.require('goog.testing.PropertyReplacer');
23 goog.require('goog.testing.TestCase');
24 goog.require('goog.testing.jsunit');
25 goog.require('goog.testing.recordFunction');
26 goog.require('goog.userAgent');
27
28 goog.setTestOnly('goog.PromiseTest');
29
30
31 function setUpPage() {
32 goog.testing.TestCase.getActiveTestCase().promiseTimeout = 10000; // 10s
33 }
34
35
36 // TODO(brenneman):
37 // - Add tests for interoperability with native Promises where available.
38 // - Add tests for long stack traces.
39
40 var SUPPORTS_ACCESSORS = !!window.Object.defineProperty &&
41 // IE8 and Safari<5.1 have an Object.defineProperty which does not work on
42 // some objects.
43 (!goog.userAgent.IE || goog.userAgent.isVersionOrHigher('9')) &&
44 (!goog.userAgent.SAFARI || goog.userAgent.isVersionOrHigher('534.48.3'));
45
46
47 var mockClock = new goog.testing.MockClock();
48 var stubs = new goog.testing.PropertyReplacer();
49 var unhandledRejections;
50
51
52 // Simple shared objects used as test values.
53 var dummy = {toString: goog.functions.constant('[object dummy]')};
54 var sentinel = {toString: goog.functions.constant('[object sentinel]')};
55
56
57 function setUp() {
58 unhandledRejections = goog.testing.recordFunction();
59 goog.Promise.setUnhandledRejectionHandler(unhandledRejections);
60 }
61
62
63 function tearDown() {
64 // The system should leave no pending unhandled rejections. Advance the mock
65 // clock (if installed) to catch any rethrows waiting in the queue.
66 mockClock.tick(Infinity);
67 mockClock.uninstall();
68 mockClock.reset();
69
70 stubs.reset();
71 }
72
73
74 /**
75 * Dummy onfulfilled or onrejected function that should not be called.
76 *
77 * @param {*} result The result passed into the callback.
78 */
79 function shouldNotCall(result) {
80 fail('This should not have been called (result: ' + String(result) + ')');
81 }
82
83
84 function fulfillSoon(value, delay) {
85 return new goog.Promise(function(resolve, reject) {
86 window.setTimeout(function() { resolve(value); }, delay);
87 });
88 }
89
90
91 function fulfillThenableSoon(value, delay) {
92 return createThenable(value, delay, true /* fulfilled */);
93 }
94
95
96 function fulfillBuiltInSoon(value, delay) {
97 // If the environment does not provide a built-in Promise, then just use
98 // goog.Promise instead to allow tests which use this to continue.
99 if (!window.Promise) {
100 return fulfillSoon(value, delay);
101 }
102 return new window.Promise(function(resolve, reject) {
103 window.setTimeout(function() { resolve(value); }, delay);
104 });
105 }
106
107
108 function rejectSoon(reason, delay) {
109 return new goog.Promise(function(resolve, reject) {
110 window.setTimeout(function() { reject(reason); }, delay);
111 });
112 }
113
114
115 function rejectThenableSoon(value, delay) {
116 return createThenable(value, delay, false /* fulfilled */);
117 }
118
119
120 function rejectBuiltInSoon(value, delay) {
121 // If the environment does not provide a built-in Promise, then just use
122 // goog.Promise instead to allow tests which use this to continue.
123 if (!window.Promise) {
124 return rejectSoon(value, delay);
125 }
126 return new window.Promise(function(resolve, reject) {
127 window.setTimeout(function() { reject(value); }, delay);
128 });
129 }
130
131
132 /**
133 * Creates a thenable which isn't formally a promise for testing non-Promise
134 * thenables.
135 */
136 function createThenableResolver() {
137 var resolver = goog.Promise.withResolver();
138 var thenable = {};
139 var then = function(onFulfilled, onRejected) {
140 var next = createThenableResolver();
141 next.resolve(resolver.promise.then(onFulfilled, onRejected));
142 return next.thenable;
143 };
144 // Count accesses of the {@code then} property when possible. Otherwise, just
145 // define the {@code then} method as a regular data property.
146 if (SUPPORTS_ACCESSORS) {
147 thenable.thenAccesses = 0;
148 window.Object.defineProperty(thenable, 'then', {
149 get: function() {
150 thenable.thenAccesses++;
151 return then;
152 }
153 });
154 } else {
155 thenable.then = then;
156 }
157 return {
158 resolve: resolver.resolve,
159 reject: resolver.reject,
160 thenable: thenable
161 };
162 }
163
164
165 /**
166 * @param {*} value The value the thenable should be fulfilled/rejected with.
167 * @param {number} delay The length of the delay until the thenable is resolved.
168 * @param {boolean} fulfill Whether to fulfill or reject the thenable.
169 * @return {!Thenable}
170 */
171 function createThenable(value, delay, fulfill) {
172 var resolver = createThenableResolver();
173 window.setTimeout(function() {
174 if (fulfill) {
175 resolver.resolve(value);
176 } else {
177 resolver.reject(value);
178 }
179 }, delay);
180 return resolver.thenable;
181 }
182
183
184 /**
185 * Creates a malicious thenable that throws when the {@code then} method is
186 * accessed to ensure that it is caught and converted to a rejected promise
187 * instead of allowed to cause a synchronous exception.
188 * @param {*} value The value to throw.
189 * @return {!Thenable}
190 */
191 function createThrowingThenable(value) {
192 // If the environment does not provide Object.defineProperty, then just
193 // use an immediately rejected promise to allow tests which use this to
194 // continue.
195 if (!SUPPORTS_ACCESSORS) {
196 return rejectThenableSoon(value, 0);
197 }
198
199 var thenable = {};
200 window.Object.defineProperty(
201 thenable, 'then', {get: function() { throw value; }});
202 return thenable;
203 }
204
205
206 function testThenIsFulfilled() {
207 var timesCalled = 0;
208
209 var p = new goog.Promise(function(resolve, reject) { resolve(sentinel); });
210 p.then(function(value) {
211 timesCalled++;
212 assertEquals(sentinel, value);
213 });
214
215 assertEquals(
216 'then() must return before callbacks are invoked.', 0, timesCalled);
217
218 return p.then(function() {
219 assertEquals('onFulfilled must be called exactly once.', 1, timesCalled);
220 });
221 }
222
223 function testThenVoidIsFulfilled() {
224 var timesCalled = 0;
225
226 var p = goog.Promise.resolve(sentinel);
227 p.thenVoid(function(value) {
228 timesCalled++;
229 assertEquals(sentinel, value);
230 });
231
232 assertEquals(
233 'thenVoid() must return before callbacks are invoked.', 0, timesCalled);
234
235 return p.then(function() {
236 assertEquals('onFulfilled must be called exactly once.', 1, timesCalled);
237 });
238 }
239
240 function testThenIsRejected() {
241 var timesCalled = 0;
242
243 var p = goog.Promise.reject(sentinel);
244 p.then(shouldNotCall, function(value) {
245 timesCalled++;
246 assertEquals(sentinel, value);
247 });
248
249 assertEquals(
250 'then() must return before callbacks are invoked.', 0, timesCalled);
251
252 return p.then(shouldNotCall, function() {
253 assertEquals('onRejected must be called exactly once.', 1, timesCalled);
254 });
255 }
256
257 function testThenVoidIsRejected() {
258 var timesCalled = 0;
259
260 var p = goog.Promise.reject(sentinel);
261 p.thenVoid(shouldNotCall, function(value) {
262 timesCalled++;
263 assertEquals(sentinel, value);
264 assertEquals('onRejected must be called exactly once.', 1, timesCalled);
265 });
266
267 assertEquals(
268 'thenVoid() must return before callbacks are invoked.', 0, timesCalled);
269
270 return p.then(shouldNotCall, function() {
271 assertEquals('onRejected must be called exactly once.', 1, timesCalled);
272 });
273 }
274
275 function testThenAsserts() {
276 var p = goog.Promise.resolve();
277
278 var m = assertThrows(function() { p.then({}); });
279 assertContains('opt_onFulfilled should be a function.', m.message);
280
281 m = assertThrows(function() { p.then(function() {}, {}); });
282 assertContains('opt_onRejected should be a function.', m.message);
283 }
284
285 function testThenVoidAsserts() {
286 var p = goog.Promise.resolve();
287
288 var m = assertThrows(function() { p.thenVoid({}); });
289 assertContains('opt_onFulfilled should be a function.', m.message);
290
291 m = assertThrows(function() { p.thenVoid(function() {}, {}); });
292 assertContains('opt_onRejected should be a function.', m.message);
293 }
294
295 function testOptionalOnFulfilled() {
296 return goog.Promise.resolve(sentinel)
297 .then(null, null)
298 .then(null, shouldNotCall)
299 .then(function(value) { assertEquals(sentinel, value); });
300 }
301
302
303 function testOptionalOnRejected() {
304 return goog.Promise.reject(sentinel)
305 .then(null, null)
306 .then(shouldNotCall)
307 .then(null, function(reason) { assertEquals(sentinel, reason); });
308 }
309
310
311 function testMultipleResolves() {
312 var timesCalled = 0;
313 var resolvePromise;
314
315 var p = new goog.Promise(function(resolve, reject) {
316 resolvePromise = resolve;
317 resolve('foo');
318 resolve('bar');
319 });
320
321 p.then(function(value) {
322 timesCalled++;
323 assertEquals('onFulfilled must be called exactly once.', 1, timesCalled);
324 });
325
326 // Add one more test for fulfilling after a delay.
327 return goog.Timer.promise(10).then(function() {
328 resolvePromise('baz');
329 assertEquals(1, timesCalled);
330 });
331 }
332
333
334 function testMultipleRejects() {
335 var timesCalled = 0;
336 var rejectPromise;
337
338 var p = new goog.Promise(function(resolve, reject) {
339 rejectPromise = reject;
340 reject('foo');
341 reject('bar');
342 });
343
344 p.then(shouldNotCall, function(value) {
345 timesCalled++;
346 assertEquals('onRejected must be called exactly once.', 1, timesCalled);
347 });
348
349 // Add one more test for rejecting after a delay.
350 return goog.Timer.promise(10).then(function() {
351 rejectPromise('baz');
352 assertEquals(1, timesCalled);
353 });
354 }
355
356
357 function testAsynchronousThenCalls() {
358 var timesCalled = [0, 0, 0, 0];
359 var p = new goog.Promise(function(resolve, reject) {
360 window.setTimeout(function() { resolve(); }, 30);
361 });
362
363 p.then(function() {
364 timesCalled[0]++;
365 assertArrayEquals([1, 0, 0, 0], timesCalled);
366 });
367
368 window.setTimeout(function() {
369 p.then(function() {
370 timesCalled[1]++;
371 assertArrayEquals([1, 1, 0, 0], timesCalled);
372 });
373 }, 10);
374
375 window.setTimeout(function() {
376 p.then(function() {
377 timesCalled[2]++;
378 assertArrayEquals([1, 1, 1, 0], timesCalled);
379 });
380 }, 20);
381
382 return goog.Timer.promise(40).then(function() {
383 return p.then(function() {
384 timesCalled[3]++;
385 assertArrayEquals([1, 1, 1, 1], timesCalled);
386 });
387 });
388 }
389
390
391 function testResolveWithPromise() {
392 var resolveBlocker;
393 var hasFulfilled = false;
394 var blocker =
395 new goog.Promise(function(resolve, reject) { resolveBlocker = resolve; });
396
397 var p = goog.Promise.resolve(blocker);
398 p.then(function(value) {
399 hasFulfilled = true;
400 assertEquals(sentinel, value);
401 }, shouldNotCall);
402
403 assertFalse(hasFulfilled);
404 resolveBlocker(sentinel);
405
406 return p.then(function() { assertTrue(hasFulfilled); });
407 }
408
409
410 function testResolveWithRejectedPromise() {
411 var rejectBlocker;
412 var hasRejected = false;
413 var blocker =
414 new goog.Promise(function(resolve, reject) { rejectBlocker = reject; });
415
416 var p = goog.Promise.resolve(blocker);
417 var child = p.then(shouldNotCall, function(reason) {
418 hasRejected = true;
419 assertEquals(sentinel, reason);
420 });
421
422 assertFalse(hasRejected);
423 rejectBlocker(sentinel);
424
425 return child.thenCatch(function() { assertTrue(hasRejected); });
426 }
427
428
429 function testRejectWithPromise() {
430 var resolveBlocker;
431 var hasFulfilled = false;
432 var blocker =
433 new goog.Promise(function(resolve, reject) { resolveBlocker = resolve; });
434
435 var p = goog.Promise.reject(blocker);
436 var child = p.then(function(value) {
437 hasFulfilled = true;
438 assertEquals(sentinel, value);
439 }, shouldNotCall);
440
441 assertFalse(hasFulfilled);
442 resolveBlocker(sentinel);
443
444 return child.thenCatch(function() { assertTrue(hasRejected); });
445 }
446
447
448 function testRejectWithRejectedPromise() {
449 var rejectBlocker;
450 var hasRejected = false;
451 var blocker =
452 new goog.Promise(function(resolve, reject) { rejectBlocker = reject; });
453
454 var p = goog.Promise.reject(blocker);
455 var child = p.then(shouldNotCall, function(reason) {
456 hasRejected = true;
457 assertEquals(sentinel, reason);
458 });
459
460 assertFalse(hasRejected);
461 rejectBlocker(sentinel);
462
463 return child.thenCatch(function() { assertTrue(hasRejected); });
464 }
465
466
467 function testResolveAndReject() {
468 var onFulfilledCalled = false;
469 var onRejectedCalled = false;
470 var p = new goog.Promise(function(resolve, reject) {
471 resolve();
472 reject();
473 });
474
475 p.then(
476 function() { onFulfilledCalled = true; },
477 function() { onRejectedCalled = true; });
478
479 return p.then(function() {
480 assertTrue(onFulfilledCalled);
481 assertFalse(onRejectedCalled);
482 });
483 }
484
485
486 function testResolveWithSelfRejects() {
487 var r;
488 var p = new goog.Promise(function(resolve) { r = resolve; });
489 r(p);
490 return p.then(shouldNotCall, function(e) {
491 assertEquals(e.message, 'Promise cannot resolve to itself');
492 });
493 }
494
495
496 function testResolveWithObjectStringResolves() {
497 return goog.Promise.resolve('[object Object]').then(function(v) {
498 assertEquals(v, '[object Object]');
499 });
500 }
501
502
503 function testRejectAndResolve() {
504 return new goog
505 .Promise(function(resolve, reject) {
506 reject();
507 resolve();
508 })
509 .then(shouldNotCall, function() { return true; });
510 }
511
512
513 function testThenReturnsBeforeCallbackWithFulfill() {
514 var thenHasReturned = false;
515 var p = goog.Promise.resolve();
516
517 var child = p.then(function() {
518 assertTrue(
519 'Callback must be called only after then() has returned.',
520 thenHasReturned);
521 });
522 thenHasReturned = true;
523
524 return child;
525 }
526
527
528 function testThenReturnsBeforeCallbackWithReject() {
529 var thenHasReturned = false;
530 var p = goog.Promise.reject();
531
532 var child = p.then(shouldNotCall, function() {
533 assertTrue(
534 'Callback must be called only after then() has returned.',
535 thenHasReturned);
536 });
537 thenHasReturned = true;
538
539 return child;
540 }
541
542
543 function testResolutionOrder() {
544 var callbacks = [];
545 return goog.Promise.resolve()
546 .then(function() { callbacks.push(1); }, shouldNotCall)
547 .then(function() { callbacks.push(2); }, shouldNotCall)
548 .then(function() { callbacks.push(3); }, shouldNotCall)
549 .then(function() {
550 assertArrayEquals([1, 2, 3], callbacks);
551 });
552 }
553
554
555 function testResolutionOrderWithThrow() {
556 var callbacks = [];
557 var p = goog.Promise.resolve();
558
559 p.then(function() { callbacks.push(1); }, shouldNotCall);
560 var child = p.then(function() {
561 callbacks.push(2);
562 throw new Error();
563 }, shouldNotCall);
564
565 child.then(shouldNotCall, function() {
566 // The parent callbacks should be evaluated before the child.
567 callbacks.push(4);
568 });
569
570 p.then(function() { callbacks.push(3); }, shouldNotCall);
571
572 return child.then(shouldNotCall, function() {
573 callbacks.push(5);
574 assertArrayEquals([1, 2, 3, 4, 5], callbacks);
575 });
576 }
577
578
579 function testResolutionOrderWithNestedThen() {
580 var resolver = goog.Promise.withResolver();
581
582 var callbacks = [];
583 var p = goog.Promise.resolve();
584
585 p.then(function() {
586 callbacks.push(1);
587 p.then(function() {
588 callbacks.push(3);
589 resolver.resolve();
590 });
591 });
592 p.then(function() { callbacks.push(2); });
593
594 return resolver.promise.then(function() {
595 assertArrayEquals([1, 2, 3], callbacks);
596 });
597 }
598
599
600 function testRejectionOrder() {
601 var callbacks = [];
602 var p = goog.Promise.reject();
603
604 p.then(shouldNotCall, function() { callbacks.push(1); });
605 p.then(shouldNotCall, function() { callbacks.push(2); });
606 p.then(shouldNotCall, function() { callbacks.push(3); });
607
608 return p.then(shouldNotCall, function() {
609 assertArrayEquals([1, 2, 3], callbacks);
610 });
611 }
612
613
614 function testRejectionOrderWithThrow() {
615 var callbacks = [];
616 var p = goog.Promise.reject();
617
618 p.then(shouldNotCall, function() { callbacks.push(1); });
619 p.then(shouldNotCall, function() {
620 callbacks.push(2);
621 throw new Error();
622 });
623 p.then(shouldNotCall, function() { callbacks.push(3); });
624
625 return p.then(shouldNotCall, function() {
626 assertArrayEquals([1, 2, 3], callbacks);
627 });
628 }
629
630
631 function testRejectionOrderWithNestedThen() {
632 var resolver = goog.Promise.withResolver();
633
634 var callbacks = [];
635 var p = goog.Promise.reject();
636
637 p.then(shouldNotCall, function() {
638 callbacks.push(1);
639 p.then(shouldNotCall, function() {
640 callbacks.push(3);
641 resolver.resolve();
642 });
643 });
644 p.then(shouldNotCall, function() { callbacks.push(2); });
645
646 return resolver.promise.then(function() {
647 assertArrayEquals([1, 2, 3], callbacks);
648 });
649 }
650
651
652 function testBranching() {
653 var p = goog.Promise.resolve(2);
654
655 var branch1 =
656 p.then(function(value) {
657 assertEquals('then functions should see the same value', 2, value);
658 return value / 2;
659 }).then(function(value) {
660 assertEquals('branch should receive the returned value', 1, value);
661 });
662
663 var branch2 =
664 p.then(function(value) {
665 assertEquals('then functions should see the same value', 2, value);
666 throw value + 1;
667 }).then(shouldNotCall, function(reason) {
668 assertEquals('branch should receive the thrown value', 3, reason);
669 });
670
671 var branch3 =
672 p.then(function(value) {
673 assertEquals('then functions should see the same value', 2, value);
674 return value * 2;
675 }).then(function(value) {
676 assertEquals('branch should receive the returned value', 4, value);
677 });
678
679 return goog.Promise.all([branch1, branch2, branch3]);
680 }
681
682
683 function testThenReturnsPromise() {
684 var parent = goog.Promise.resolve();
685 var child = parent.then();
686
687 assertTrue(child instanceof goog.Promise);
688 assertNotEquals(
689 'The returned Promise must be different from the input.', parent, child);
690 }
691
692
693 function testThenVoidReturnsUndefined() {
694 var parent = goog.Promise.resolve();
695 var child = parent.thenVoid();
696
697 assertUndefined(child);
698 }
699
700
701 function testBlockingPromise() {
702 var p = goog.Promise.resolve();
703 var wasFulfilled = false;
704 var wasRejected = false;
705
706 var p2 = p.then(function() {
707 return new goog.Promise(function(resolve, reject) {});
708 });
709
710 p2.then(
711 function() { wasFulfilled = true; }, function() { wasRejected = true; });
712
713 return goog.Timer.promise(10).then(function() {
714 assertFalse('p2 should be blocked on the returned Promise', wasFulfilled);
715 assertFalse('p2 should be blocked on the returned Promise', wasRejected);
716 });
717 }
718
719
720 function testBlockingPromiseFulfilled() {
721 var blockingPromise = new goog.Promise(function(resolve, reject) {
722 window.setTimeout(function() { resolve(sentinel); }, 0);
723 });
724
725 var p = goog.Promise.resolve(dummy);
726 var p2 = p.then(function(value) { return blockingPromise; });
727
728 return p2.then(function(value) { assertEquals(sentinel, value); });
729 }
730
731
732 function testBlockingPromiseRejected() {
733 var blockingPromise = new goog.Promise(function(resolve, reject) {
734 window.setTimeout(function() { reject(sentinel); }, 0);
735 });
736
737 var p = goog.Promise.resolve(blockingPromise);
738
739 return p.then(
740 shouldNotCall, function(reason) { assertEquals(sentinel, reason); });
741 }
742
743
744 function testBlockingThenableFulfilled() {
745 var thenable = {then: function(onFulfill, onReject) { onFulfill(sentinel); }};
746
747 return goog.Promise.resolve(thenable).then(function(reason) {
748 assertEquals(sentinel, reason);
749 });
750 }
751
752
753 function testBlockingThenableRejected() {
754 var thenable = {then: function(onFulfill, onReject) { onReject(sentinel); }};
755
756 return goog.Promise.resolve(thenable).then(
757 shouldNotCall, function(reason) { assertEquals(sentinel, reason); });
758 }
759
760
761 function testBlockingThenableThrows() {
762 var thenable = {then: function(onFulfill, onReject) { throw sentinel; }};
763
764 return goog.Promise.resolve(thenable).then(
765 shouldNotCall, function(reason) { assertEquals(sentinel, reason); });
766 }
767
768
769 function testBlockingThenableMisbehaves() {
770 var thenable = {
771 then: function(onFulfill, onReject) {
772 onFulfill(sentinel);
773 onFulfill(dummy);
774 onReject(dummy);
775 throw dummy;
776 }
777 };
778
779 return goog.Promise.resolve(thenable).then(function(value) {
780 assertEquals(
781 'Only the first resolution of the Thenable should have a result.',
782 sentinel, value);
783 });
784 }
785
786
787 function testNestingThenables() {
788 var thenableA = {
789 then: function(onFulfill, onReject) { onFulfill(sentinel); }
790 };
791 var thenableB = {
792 then: function(onFulfill, onReject) { onFulfill(thenableA); }
793 };
794 var thenableC = {
795 then: function(onFulfill, onReject) { onFulfill(thenableB); }
796 };
797
798 return goog.Promise.resolve(thenableC).then(function(value) {
799 assertEquals(
800 'Should resolve to the fulfillment value of thenableA', sentinel,
801 value);
802 });
803 }
804
805
806 function testNestingThenablesRejected() {
807 var thenableA = {then: function(onFulfill, onReject) { onReject(sentinel); }};
808 var thenableB = {
809 then: function(onFulfill, onReject) { onReject(thenableA); }
810 };
811 var thenableC = {
812 then: function(onFulfill, onReject) { onReject(thenableB); }
813 };
814
815 return goog.Promise.reject(thenableC).then(shouldNotCall, function(reason) {
816 assertEquals(
817 'Should resolve to rejection reason of thenableA', sentinel, reason);
818 });
819 }
820
821
822 function testThenCatch() {
823 var catchCalled = false;
824 return goog.Promise.reject()
825 .thenCatch(function(reason) {
826 catchCalled = true;
827 return sentinel;
828 })
829 .then(function(value) {
830 assertTrue(catchCalled);
831 assertEquals(sentinel, value);
832 });
833 }
834
835
836 function testRaceWithEmptyList() {
837 return goog.Promise.race([]).then(function(value) {
838 assertUndefined(value);
839 });
840 }
841
842
843 function testRaceWithFulfill() {
844 var a = fulfillSoon('a', 40);
845 var b = fulfillSoon('b', 30);
846 var c = fulfillSoon('c', 10);
847 var d = fulfillSoon('d', 20);
848
849 return goog.Promise.race([a, b, c, d])
850 .then(function(value) {
851 assertEquals('c', value);
852 // Return the slowest input promise to wait for it to complete.
853 return a;
854 })
855 .then(function(value) {
856 assertEquals(
857 'The slowest promise should resolve eventually.', 'a', value);
858 });
859 }
860
861
862 function testRaceWithThenables() {
863 var a = fulfillThenableSoon('a', 40);
864 var b = fulfillThenableSoon('b', 30);
865 var c = fulfillThenableSoon('c', 10);
866 var d = fulfillThenableSoon('d', 20);
867
868 return goog.Promise.race([a, b, c, d])
869 .then(function(value) {
870 assertEquals('c', value);
871 // Ensure that the {@code then} property was only accessed once by
872 // {@code goog.Promise.race}.
873 if (SUPPORTS_ACCESSORS) {
874 assertEquals(1, c.thenAccesses);
875 }
876 // Return the slowest input thenable to wait for it to complete.
877 return a;
878 })
879 .then(function(value) {
880 assertEquals(
881 'The slowest thenable should resolve eventually.', 'a', value);
882 });
883 }
884
885
886 function testRaceWithBuiltIns() {
887 var a = fulfillBuiltInSoon('a', 40);
888 var b = fulfillBuiltInSoon('b', 30);
889 var c = fulfillBuiltInSoon('c', 10);
890 var d = fulfillBuiltInSoon('d', 20);
891
892 return goog.Promise.race([a, b, c, d])
893 .then(function(value) {
894 assertEquals('c', value);
895 // Return the slowest input promise to wait for it to complete.
896 return a;
897 })
898 .then(function(value) {
899 assertEquals(
900 'The slowest promise should resolve eventually.', 'a', value);
901 });
902 }
903
904
905 function testRaceWithNonThenable() {
906 var a = fulfillSoon('a', 40);
907 var b = 'b';
908 var c = fulfillSoon('c', 10);
909 var d = fulfillSoon('d', 20);
910
911 return goog.Promise.race([a, b, c, d])
912 .then(function(value) {
913 assertEquals('b', value);
914 // Return the slowest input promise to wait for it to complete.
915 return a;
916 })
917 .then(function(value) {
918 assertEquals(
919 'The slowest promise should resolve eventually.', 'a', value);
920 });
921 }
922
923
924 function testRaceWithFalseyNonThenable() {
925 var a = fulfillSoon('a', 40);
926 var b = 0;
927 var c = fulfillSoon('c', 10);
928 var d = fulfillSoon('d', 20);
929
930 return goog.Promise.race([a, b, c, d])
931 .then(function(value) {
932 assertEquals(0, value);
933 // Return the slowest input promise to wait for it to complete.
934 return a;
935 })
936 .then(function(value) {
937 assertEquals(
938 'The slowest promise should resolve eventually.', 'a', value);
939 });
940 }
941
942
943 function testRaceWithFulfilledBeforeNonThenable() {
944 var a = fulfillSoon('a', 40);
945 var b = goog.Promise.resolve('b');
946 var c = 'c';
947 var d = fulfillSoon('d', 20);
948
949 return goog.Promise.race([a, b, c, d])
950 .then(function(value) {
951 assertEquals('b', value);
952 // Return the slowest input promise to wait for it to complete.
953 return a;
954 })
955 .then(function(value) {
956 assertEquals(
957 'The slowest promise should resolve eventually.', 'a', value);
958 });
959 }
960
961
962 function testRaceWithReject() {
963 var a = rejectSoon('rejected-a', 40);
964 var b = rejectSoon('rejected-b', 30);
965 var c = rejectSoon('rejected-c', 10);
966 var d = rejectSoon('rejected-d', 20);
967
968 return goog.Promise.race([a, b, c, d])
969 .then(
970 shouldNotCall,
971 function(value) {
972 assertEquals('rejected-c', value);
973 return a;
974 })
975 .then(shouldNotCall, function(reason) {
976 assertEquals(
977 'The slowest promise should resolve eventually.', 'rejected-a',
978 reason);
979 });
980 }
981
982 function testRaceWithRejectThenable() {
983 var a = rejectThenableSoon('rejected-a', 40);
984 var b = rejectThenableSoon('rejected-b', 30);
985 var c = rejectThenableSoon('rejected-c', 10);
986 var d = rejectThenableSoon('rejected-d', 20);
987
988 return goog.Promise.race([a, b, c, d])
989 .then(
990 shouldNotCall,
991 function(value) {
992 assertEquals('rejected-c', value);
993 return a;
994 })
995 .then(shouldNotCall, function(reason) {
996 assertEquals(
997 'The slowest promise should resolve eventually.', 'rejected-a',
998 reason);
999 });
1000 }
1001
1002 function testRaceWithRejectBuiltIn() {
1003 var a = rejectBuiltInSoon('rejected-a', 40);
1004 var b = rejectBuiltInSoon('rejected-b', 30);
1005 var c = rejectBuiltInSoon('rejected-c', 10);
1006 var d = rejectBuiltInSoon('rejected-d', 20);
1007
1008 return goog.Promise.race([a, b, c, d])
1009 .then(
1010 shouldNotCall,
1011 function(value) {
1012 assertEquals('rejected-c', value);
1013 return a;
1014 })
1015 .then(shouldNotCall, function(reason) {
1016 assertEquals(
1017 'The slowest promise should resolve eventually.', 'rejected-a',
1018 reason);
1019 });
1020 }
1021
1022 function testRaceWithRejectAndThrowingThenable() {
1023 var a = rejectSoon('rejected-a', 40);
1024 var b = rejectThenableSoon('rejected-b', 30);
1025 var c = rejectBuiltInSoon('rejected-c', 10);
1026 var d = createThrowingThenable('rejected-d');
1027
1028 return goog.Promise.race([a, b, c, d])
1029 .then(
1030 shouldNotCall,
1031 function(value) {
1032 assertEquals('rejected-d', value);
1033 return a;
1034 })
1035 .then(shouldNotCall, function(reason) {
1036 assertEquals(
1037 'The slowest promise should resolve eventually.', 'rejected-a',
1038 reason);
1039 });
1040 }
1041
1042
1043 function testAllWithEmptyList() {
1044 return goog.Promise.all([]).then(function(value) {
1045 assertArrayEquals([], value);
1046 });
1047 }
1048
1049
1050 function testAllWithFulfill() {
1051 var a = fulfillSoon('a', 40);
1052 var b = fulfillSoon('b', 30);
1053 var c = fulfillSoon('c', 10);
1054 var d = fulfillSoon('d', 20);
1055 // Test a falsey value.
1056 var z = fulfillSoon(0, 30);
1057
1058 return goog.Promise.all([a, b, c, d, z]).then(function(value) {
1059 assertArrayEquals(['a', 'b', 'c', 'd', 0], value);
1060 });
1061 }
1062
1063
1064 function testAllWithThenable() {
1065 var a = fulfillSoon('a', 40);
1066 var b = fulfillThenableSoon('b', 30);
1067 var c = fulfillSoon('c', 10);
1068 var d = fulfillSoon('d', 20);
1069
1070 return goog.Promise.all([a, b, c, d]).then(function(value) {
1071 assertArrayEquals(['a', 'b', 'c', 'd'], value);
1072 // Ensure that the {@code then} property was only accessed once by
1073 // {@code goog.Promise.all}.
1074 if (SUPPORTS_ACCESSORS) {
1075 assertEquals(1, b.thenAccesses);
1076 }
1077 });
1078 }
1079
1080
1081 function testAllWithBuiltIn() {
1082 var a = fulfillSoon('a', 40);
1083 var b = fulfillBuiltInSoon('b', 30);
1084 var c = fulfillSoon('c', 10);
1085 var d = fulfillSoon('d', 20);
1086
1087 return goog.Promise.all([a, b, c, d]).then(function(value) {
1088 assertArrayEquals(['a', 'b', 'c', 'd'], value);
1089 });
1090 }
1091
1092
1093 function testAllWithNonThenable() {
1094 var a = fulfillSoon('a', 40);
1095 var b = 'b';
1096 var c = fulfillSoon('c', 10);
1097 var d = fulfillSoon('d', 20);
1098 // Test a falsey value.
1099 var z = 0;
1100
1101 return goog.Promise.all([a, b, c, d, z]).then(function(value) {
1102 assertArrayEquals(['a', 'b', 'c', 'd', 0], value);
1103 });
1104 }
1105
1106
1107 function testAllWithReject() {
1108 var a = fulfillSoon('a', 40);
1109 var b = rejectSoon('rejected-b', 30);
1110 var c = fulfillSoon('c', 10);
1111 var d = fulfillSoon('d', 20);
1112
1113 return goog.Promise.all([a, b, c, d])
1114 .then(
1115 shouldNotCall,
1116 function(reason) {
1117 assertEquals('rejected-b', reason);
1118 return a;
1119 })
1120 .then(function(value) {
1121 assertEquals(
1122 'Promise "a" should be fulfilled even though the all()' +
1123 'was rejected.',
1124 'a', value);
1125 });
1126 }
1127
1128
1129 function testAllSettledWithEmptyList() {
1130 return goog.Promise.allSettled([]).then(function(results) {
1131 assertArrayEquals([], results);
1132 });
1133 }
1134
1135
1136 function testAllSettledWithFulfillAndReject() {
1137 var a = fulfillSoon('a', 40);
1138 var b = rejectSoon('rejected-b', 30);
1139 var c = 'c';
1140 var d = rejectBuiltInSoon('rejected-d', 20);
1141 var e = fulfillThenableSoon('e', 40);
1142 var f = fulfillBuiltInSoon('f', 30);
1143 var g = rejectThenableSoon('rejected-g', 10);
1144 var h = createThrowingThenable('rejected-h');
1145 // Test a falsey value.
1146 var z = 0;
1147
1148 return goog.Promise.allSettled([a, b, c, d, e, f, g, h, z])
1149 .then(function(results) {
1150 assertArrayEquals(
1151 [
1152 {fulfilled: true, value: 'a'},
1153 {fulfilled: false, reason: 'rejected-b'},
1154 {fulfilled: true, value: 'c'},
1155 {fulfilled: false, reason: 'rejected-d'},
1156 {fulfilled: true, value: 'e'}, {fulfilled: true, value: 'f'},
1157 {fulfilled: false, reason: 'rejected-g'},
1158 {fulfilled: false, reason: 'rejected-h'},
1159 {fulfilled: true, value: 0}
1160 ],
1161 results);
1162 // Ensure that the {@code then} property was only accessed once by
1163 // {@code goog.Promise.allSettled}.
1164 if (SUPPORTS_ACCESSORS) {
1165 assertEquals(1, e.thenAccesses);
1166 assertEquals(1, g.thenAccesses);
1167 }
1168 });
1169 }
1170
1171
1172 function testFirstFulfilledWithEmptyList() {
1173 return goog.Promise.firstFulfilled([]).then(function(value) {
1174 assertUndefined(value);
1175 });
1176 }
1177
1178
1179 function testFirstFulfilledWithFulfill() {
1180 var a = fulfillSoon('a', 40);
1181 var b = rejectSoon('rejected-b', 30);
1182 var c = rejectSoon('rejected-c', 10);
1183 var d = fulfillSoon('d', 20);
1184
1185 return goog.Promise.firstFulfilled([a, b, c, d])
1186 .then(function(value) {
1187 assertEquals('d', value);
1188 return c;
1189 })
1190 .then(
1191 shouldNotCall,
1192 function(reason) {
1193 assertEquals(
1194 'Promise "c" should be rejected before firstFulfilled() resolves.',
1195 'rejected-c', reason);
1196 return a;
1197 })
1198 .then(function(value) {
1199 assertEquals(
1200 'Promise "a" should be fulfilled after firstFulfilled() resolves.',
1201 'a', value);
1202 });
1203 }
1204
1205
1206 function testFirstFulfilledWithThenables() {
1207 var a = fulfillThenableSoon('a', 40);
1208 var b = rejectThenableSoon('rejected-b', 30);
1209 var c = rejectThenableSoon('rejected-c', 10);
1210 var d = fulfillThenableSoon('d', 20);
1211
1212 return goog.Promise.firstFulfilled([a, b, c, d])
1213 .then(function(value) {
1214 assertEquals('d', value);
1215 // Ensure that the {@code then} property was only accessed once by
1216 // {@code goog.Promise.firstFulfilled}.
1217 if (SUPPORTS_ACCESSORS) {
1218 assertEquals(1, d.thenAccesses);
1219 }
1220 return c;
1221 })
1222 .then(
1223 shouldNotCall,
1224 function(reason) {
1225 assertEquals(
1226 'Thenable "c" should be rejected before firstFulfilled() resolves.',
1227 'rejected-c', reason);
1228 return a;
1229 })
1230 .then(function(value) {
1231 assertEquals(
1232 'Thenable "a" should be fulfilled after firstFulfilled() resolves.',
1233 'a', value);
1234 });
1235 }
1236
1237
1238 function testFirstFulfilledWithBuiltIns() {
1239 var a = fulfillBuiltInSoon('a', 40);
1240 var b = rejectBuiltInSoon('rejected-b', 30);
1241 var c = rejectBuiltInSoon('rejected-c', 10);
1242 var d = fulfillBuiltInSoon('d', 20);
1243
1244 return goog.Promise.firstFulfilled([a, b, c, d])
1245 .then(function(value) {
1246 assertEquals('d', value);
1247 return c;
1248 })
1249 .then(
1250 shouldNotCall,
1251 function(reason) {
1252 assertEquals(
1253 'Promise "c" should be rejected before firstFulfilled() resolves.',
1254 'rejected-c', reason);
1255 return a;
1256 })
1257 .then(function(value) {
1258 assertEquals(
1259 'Promise "a" should be fulfilled after firstFulfilled() resolves.',
1260 'a', value);
1261 });
1262 }
1263
1264
1265 function testFirstFulfilledWithNonThenable() {
1266 var a = fulfillSoon('a', 40);
1267 var b = rejectSoon('rejected-b', 30);
1268 var c = rejectSoon('rejected-c', 10);
1269 var d = 'd';
1270
1271 return goog.Promise.firstFulfilled([a, b, c, d])
1272 .then(function(value) {
1273 assertEquals('d', value);
1274 // Return the slowest input promise to wait for it to complete.
1275 return a;
1276 })
1277 .then(function(value) {
1278 assertEquals(
1279 'The slowest promise should resolve eventually.', 'a', value);
1280 });
1281 }
1282
1283
1284 function testFirstFulfilledWithFalseyNonThenable() {
1285 var a = fulfillSoon('a', 40);
1286 var b = rejectSoon('rejected-b', 30);
1287 var c = rejectSoon('rejected-c', 10);
1288 var d = 0;
1289
1290 return goog.Promise.firstFulfilled([a, b, c, d])
1291 .then(function(value) {
1292 assertEquals(0, value);
1293 // Return the slowest input promise to wait for it to complete.
1294 return a;
1295 })
1296 .then(function(value) {
1297 assertEquals(
1298 'The slowest promise should resolve eventually.', 'a', value);
1299 });
1300 }
1301
1302
1303 function testFirstFulfilledWithFulfilledBeforeNonThenable() {
1304 var a = fulfillSoon('a', 40);
1305 var b = goog.Promise.resolve('b');
1306 var c = rejectSoon('rejected-c', 10);
1307 var d = 'd';
1308
1309 return goog.Promise.firstFulfilled([a, b, c, d])
1310 .then(function(value) {
1311 assertEquals('b', value);
1312 // Return the slowest input promise to wait for it to complete.
1313 return a;
1314 })
1315 .then(function(value) {
1316 assertEquals(
1317 'The slowest promise should resolve eventually.', 'a', value);
1318 });
1319 }
1320
1321
1322 function testFirstFulfilledWithReject() {
1323 var a = rejectSoon('rejected-a', 40);
1324 var b = rejectThenableSoon('rejected-b', 30);
1325 var c = rejectBuiltInSoon('rejected-c', 10);
1326 var d = createThrowingThenable('rejected-d');
1327
1328 return goog.Promise.firstFulfilled([a, b, c, d])
1329 .then(shouldNotCall, function(reason) {
1330 assertArrayEquals(
1331 ['rejected-a', 'rejected-b', 'rejected-c', 'rejected-d'], reason);
1332 // Ensure that the {@code then} property was only accessed once by
1333 // {@code goog.Promise.firstFulfilled}.
1334 if (SUPPORTS_ACCESSORS) {
1335 assertEquals(1, b.thenAccesses);
1336 }
1337 });
1338 }
1339
1340
1341 function testThenAlwaysWithFulfill() {
1342 var thenAlwaysCalled = false;
1343 return goog.Promise.resolve(sentinel)
1344 .thenAlways(function() {
1345 assertEquals(
1346 'thenAlways should have no arguments', 0, arguments.length);
1347 thenAlwaysCalled = true;
1348 })
1349 .then(function(value) {
1350 assertEquals(sentinel, value);
1351 assertTrue(thenAlwaysCalled);
1352 });
1353 }
1354
1355
1356 function testThenAlwaysWithReject() {
1357 var thenAlwaysCalled = false;
1358 return goog.Promise.reject(sentinel)
1359 .thenAlways(function(arg) {
1360 assertEquals(
1361 'thenAlways should have no arguments', 0, arguments.length);
1362 thenAlwaysCalled = true;
1363 })
1364 .then(shouldNotCall, function(err) {
1365 assertEquals(sentinel, err);
1366 return null;
1367 });
1368 }
1369
1370
1371 function testThenAlwaysCalledMultipleTimes() {
1372 var calls = [];
1373
1374 var p = goog.Promise.resolve(sentinel);
1375 p.then(function(value) {
1376 assertEquals(sentinel, value);
1377 calls.push(1);
1378 return value;
1379 });
1380 p.thenAlways(function() {
1381 assertEquals(0, arguments.length);
1382 calls.push(2);
1383 throw new Error('thenAlways throw');
1384 });
1385 p.then(function(value) {
1386 assertEquals(
1387 'Promise result should not mutate after throw from thenAlways.',
1388 sentinel, value);
1389 calls.push(3);
1390 });
1391 p.thenAlways(function() { assertArrayEquals([1, 2, 3], calls); });
1392 p.thenAlways(function() {
1393 assertEquals(
1394 'Should be one unhandled exception from the "thenAlways throw".', 1,
1395 unhandledRejections.getCallCount());
1396 var rejectionCall = unhandledRejections.popLastCall();
1397 assertEquals(1, rejectionCall.getArguments().length);
1398 var err = rejectionCall.getArguments()[0];
1399 assertEquals('thenAlways throw', err.message);
1400 assertEquals(goog.global, rejectionCall.getThis());
1401 });
1402
1403 return p.thenAlways(function() { assertEquals(3, calls.length); });
1404 }
1405
1406
1407 function testContextWithInit() {
1408 var initContext;
1409 var p = new goog.Promise(function(resolve, reject) {
1410 initContext = this;
1411 }, sentinel);
1412 assertEquals(sentinel, initContext);
1413 }
1414
1415
1416 function testContextWithInitDefault() {
1417 var initContext;
1418 var p = new goog.Promise(function(resolve, reject) { initContext = this; });
1419 assertEquals(
1420 'initFunc should default to being called in the global scope',
1421 goog.global, initContext);
1422 }
1423
1424
1425 function testContextWithFulfillment() {
1426 return goog.Promise.resolve()
1427 .then(function() {
1428 assertEquals(
1429 'Call should be made in the global scope if no context is specified.',
1430 goog.global, this);
1431 })
1432 .then(
1433 function() { assertEquals(sentinel, this); }, shouldNotCall, sentinel)
1434 .thenAlways(function() { assertEquals(sentinel, this); }, sentinel);
1435 }
1436
1437
1438 function testContextWithRejection() {
1439 return goog.Promise.reject()
1440 .then(
1441 shouldNotCall,
1442 function() {
1443 assertEquals(
1444 'Call should be in the default scope when no context is set.',
1445 goog.global, this);
1446 throw new Error('Intentional rejection');
1447 })
1448 .then(
1449 shouldNotCall, function() { assertEquals(sentinel, this); }, sentinel)
1450 .thenAlways(function() { assertEquals(sentinel, this); }, sentinel)
1451 .thenCatch(function() { assertEquals(sentinel, this); }, sentinel);
1452 }
1453
1454
1455 function testCancel() {
1456 var p = new goog.Promise(goog.nullFunction);
1457 var child = p.then(shouldNotCall, function(reason) {
1458 assertTrue(reason instanceof goog.Promise.CancellationError);
1459 assertEquals('cancellation message', reason.message);
1460
1461 // Return a non-Error to resolve the cancellation rejection.
1462 return null;
1463 });
1464 p.cancel('cancellation message');
1465 return child;
1466 }
1467
1468
1469 function testThenVoidCancel() {
1470 var thenVoidCalled = false;
1471 var p = new goog.Promise(goog.nullFunction);
1472
1473 p.thenVoid(shouldNotCall, function(reason) {
1474 assertTrue(reason instanceof goog.Promise.CancellationError);
1475 assertEquals('cancellation message', reason.message);
1476 thenVoidCalled = true;
1477 });
1478
1479 p.cancel('cancellation message');
1480 assertFalse(thenVoidCalled);
1481
1482 return p.thenCatch(function() {
1483 assertTrue(thenVoidCalled);
1484
1485 // Return a non-Error to resolve the cancellation rejection.
1486 return null;
1487 });
1488 }
1489
1490
1491 function testCancelAfterResolve() {
1492 var p = goog.Promise.resolve();
1493 p.cancel();
1494 return p.then(null, shouldNotCall);
1495 }
1496
1497
1498 function testThenVoidCancelAfterResolve() {
1499 var p = goog.Promise.resolve();
1500 p.cancel();
1501 p.thenVoid(null, shouldNotCall);
1502 return p;
1503 }
1504
1505
1506 function testCancelAfterReject() {
1507 var p = goog.Promise.reject(sentinel);
1508 p.cancel();
1509 return p.then(
1510 shouldNotCall, function(reason) { assertEquals(sentinel, reason); });
1511 }
1512
1513
1514 function testThenVoidCancelAfterReject() {
1515 var thenVoidCalled = false;
1516 var p = goog.Promise.reject(sentinel);
1517 p.cancel();
1518
1519 p.thenVoid(shouldNotCall, function(reason) {
1520 assertEquals(sentinel, reason);
1521 thenVoidCalled = true;
1522 });
1523
1524 return p.thenCatch(function() { assertTrue(thenVoidCalled); });
1525 }
1526
1527
1528 function testCancelPropagation() {
1529 var cancelError;
1530 var p = new goog.Promise(goog.nullFunction);
1531
1532 var p2 = p.then(shouldNotCall, function(reason) {
1533 cancelError = reason;
1534 assertTrue(reason instanceof goog.Promise.CancellationError);
1535 assertEquals('parent cancel message', reason.message);
1536 return sentinel;
1537 }).then(function(value) {
1538 assertEquals(
1539 'Child promises should receive the returned value of the parent.',
1540 sentinel, value);
1541 }, shouldNotCall);
1542
1543 var p3 = p.then(shouldNotCall, function(reason) {
1544 assertEquals(
1545 'Every onRejected handler should receive the same cancel error.',
1546 cancelError, reason);
1547 assertEquals('parent cancel message', reason.message);
1548
1549 // Return a non-Error to resolve the cancellation rejection.
1550 return null;
1551 });
1552
1553 p.cancel('parent cancel message');
1554 return goog.Promise.all([p2, p3]);
1555 }
1556
1557
1558 function testThenVoidCancelPropagation() {
1559 var resolver = goog.Promise.withResolver();
1560 var toResolveCount = 2;
1561
1562 var partialResolve = function() {
1563 if (--toResolveCount == 0) {
1564 resolver.resolve();
1565 }
1566 };
1567
1568 var cancelError;
1569 var p = new goog.Promise(goog.nullFunction);
1570
1571 var p2 = p.then(shouldNotCall, function(reason) {
1572 cancelError = reason;
1573 assertTrue(reason instanceof goog.Promise.CancellationError);
1574 assertEquals('parent cancel message', reason.message);
1575 return sentinel;
1576 });
1577 p2.thenVoid(function(value) {
1578 assertEquals(
1579 'Child promises should receive the returned value of the parent.',
1580 sentinel, value);
1581 partialResolve();
1582 }, shouldNotCall);
1583
1584 p.thenVoid(shouldNotCall, function(reason) {
1585 assertEquals(
1586 'Every onRejected handler should receive the same cancel error.',
1587 cancelError, reason);
1588 assertEquals('parent cancel message', reason.message);
1589 partialResolve();
1590 });
1591
1592 p.cancel('parent cancel message');
1593 return resolver.promise;
1594 }
1595
1596
1597 function testCancelPropagationUpward() {
1598 var cancelError;
1599 var cancelCalls = [];
1600 var parent = new goog.Promise(goog.nullFunction);
1601
1602 var child = parent.then(shouldNotCall, function(reason) {
1603 assertTrue(reason instanceof goog.Promise.CancellationError);
1604 assertEquals('grandChild cancel message', reason.message);
1605 cancelError = reason;
1606 cancelCalls.push('parent');
1607 });
1608
1609 var grandChild = child.then(shouldNotCall, function(reason) {
1610 assertEquals(
1611 'Child should receive the same cancel error.', cancelError, reason);
1612 cancelCalls.push('child');
1613 });
1614
1615 var descendant = grandChild.then(shouldNotCall, function(reason) {
1616 assertEquals(
1617 'GrandChild should receive the same cancel error.', cancelError,
1618 reason);
1619 cancelCalls.push('grandChild');
1620
1621 assertArrayEquals(
1622 'Each promise in the hierarchy has a single child, so canceling the ' +
1623 'grandChild should cancel each ancestor in order.',
1624 ['parent', 'child', 'grandChild'], cancelCalls);
1625
1626 // Return a non-Error to resolve the cancellation rejection.
1627 return null;
1628 });
1629
1630 grandChild.cancel('grandChild cancel message');
1631 return descendant;
1632 }
1633
1634
1635 function testThenVoidCancelPropagationUpward() {
1636 var cancelError;
1637 var cancelCalls = [];
1638 var parent = new goog.Promise(goog.nullFunction);
1639
1640 var child = parent.then(shouldNotCall, function(reason) {
1641 assertTrue(reason instanceof goog.Promise.CancellationError);
1642 assertEquals('grandChild cancel message', reason.message);
1643 cancelError = reason;
1644 cancelCalls.push('parent');
1645 });
1646
1647 var grandChild = child.then(shouldNotCall, function(reason) {
1648 assertEquals(
1649 'Child should receive the same cancel error.', cancelError, reason);
1650 cancelCalls.push('child');
1651 });
1652
1653 grandChild.thenVoid(shouldNotCall, function(reason) {
1654 assertEquals(
1655 'GrandChild should receive the same cancel error.', cancelError,
1656 reason);
1657 cancelCalls.push('grandChild');
1658 });
1659
1660 grandChild.cancel('grandChild cancel message');
1661 return grandChild.thenCatch(function(reason) {
1662 assertEquals(cancelError, reason);
1663 assertArrayEquals(
1664 'Each promise in the hierarchy has a single child, so canceling the ' +
1665 'grandChild should cancel each ancestor in order.',
1666 ['parent', 'child', 'grandChild'], cancelCalls);
1667
1668 // Return a non-Error to resolve the cancellation rejection.
1669 return null;
1670 });
1671 }
1672
1673
1674 function testCancelPropagationUpwardWithMultipleChildren() {
1675 var cancelError;
1676 var cancelCalls = [];
1677 var parent = fulfillSoon(sentinel, 0);
1678
1679 parent.then(function(value) {
1680 assertEquals(
1681 'Non-canceled callbacks should be called after a sibling is canceled.',
1682 sentinel, value);
1683 });
1684
1685 var child = parent.then(shouldNotCall, function(reason) {
1686 assertTrue(reason instanceof goog.Promise.CancellationError);
1687 assertEquals('grandChild cancel message', reason.message);
1688 cancelError = reason;
1689 cancelCalls.push('child');
1690 });
1691
1692 var grandChild = child.then(shouldNotCall, function(reason) {
1693 assertEquals(reason, cancelError);
1694 cancelCalls.push('grandChild');
1695 });
1696 grandChild.cancel('grandChild cancel message');
1697
1698 return grandChild.then(shouldNotCall, function(reason) {
1699 assertEquals(reason, cancelError);
1700 assertArrayEquals(
1701 'The parent promise has multiple children, so only the child and ' +
1702 'grandChild should be canceled.',
1703 ['child', 'grandChild'], cancelCalls);
1704
1705 // Return a non-Error to resolve the cancellation rejection.
1706 return null;
1707 });
1708 }
1709
1710
1711 function testThenVoidCancelPropagationUpwardWithMultipleChildren() {
1712 var cancelError;
1713 var cancelCalls = [];
1714 var parent = fulfillSoon(sentinel, 0);
1715
1716 parent.thenVoid(function(value) {
1717 assertEquals(
1718 'Non-canceled callbacks should be called after a sibling is canceled.',
1719 sentinel, value);
1720 }, shouldNotCall);
1721
1722 var child = parent.then(shouldNotCall, function(reason) {
1723 assertTrue(reason instanceof goog.Promise.CancellationError);
1724 assertEquals('grandChild cancel message', reason.message);
1725 cancelError = reason;
1726 cancelCalls.push('child');
1727 });
1728
1729 var grandChild = child.then(shouldNotCall, function(reason) {
1730 assertEquals(reason, cancelError);
1731 cancelCalls.push('grandChild');
1732 });
1733 grandChild.cancel('grandChild cancel message');
1734
1735 grandChild.thenVoid(shouldNotCall, function(reason) {
1736 assertEquals(reason, cancelError);
1737 cancelCalls.push('void grandChild');
1738 });
1739
1740 return grandChild.then(shouldNotCall, function(reason) {
1741 assertEquals(reason, cancelError);
1742 assertArrayEquals(
1743 'The parent promise has multiple children, so only the child and ' +
1744 'grandChildren should be canceled.',
1745 ['child', 'grandChild', 'void grandChild'], cancelCalls);
1746
1747 // Return a non-Error to resolve the cancellation rejection.
1748 return null;
1749 });
1750 }
1751
1752
1753 function testCancelRecovery() {
1754 var cancelError;
1755 var cancelCalls = [];
1756
1757 var parent = fulfillSoon(sentinel, 100);
1758
1759 var sibling1 = parent.then(function(value) {
1760 assertEquals(
1761 'Non-canceled callbacks should be called after a sibling is canceled.',
1762 sentinel, value);
1763 });
1764
1765 var sibling2 = parent.then(shouldNotCall, function(reason) {
1766 assertTrue(reason instanceof goog.Promise.CancellationError);
1767 cancelError = reason;
1768 cancelCalls.push('sibling2');
1769 return sentinel;
1770 });
1771
1772 var grandChild = sibling2.then(function(value) {
1773 cancelCalls.push('child');
1774 assertEquals(
1775 'Returning a non-cancel value should uncancel the grandChild.', value,
1776 sentinel);
1777 assertArrayEquals(['sibling2', 'child'], cancelCalls);
1778 }, shouldNotCall);
1779
1780 grandChild.cancel();
1781 return goog.Promise.all([sibling1, grandChild]);
1782 }
1783
1784
1785 function testCancellationError() {
1786 var err = new goog.Promise.CancellationError('cancel message');
1787 assertTrue(err instanceof Error);
1788 assertTrue(err instanceof goog.Promise.CancellationError);
1789 assertEquals('cancel', err.name);
1790 assertEquals('cancel message', err.message);
1791 }
1792
1793
1794 function testMockClock() {
1795 mockClock.install();
1796
1797 var resolveA;
1798 var resolveB;
1799 var calls = [];
1800
1801 var p = new goog.Promise(function(resolve, reject) { resolveA = resolve; });
1802
1803 p.then(function(value) {
1804 assertEquals(sentinel, value);
1805 calls.push('then');
1806 });
1807
1808 var fulfilledChild = p.then(function(value) {
1809 assertEquals(sentinel, value);
1810 return goog.Promise.resolve(1);
1811 }).then(function(value) {
1812 assertEquals(1, value);
1813 calls.push('fulfilledChild');
1814
1815 });
1816
1817 var rejectedChild = p.then(function(value) {
1818 assertEquals(sentinel, value);
1819 return goog.Promise.reject(2);
1820 }).then(shouldNotCall, function(reason) {
1821 assertEquals(2, reason);
1822 calls.push('rejectedChild');
1823 });
1824
1825 var unresolvedChild =
1826 p.then(function(value) {
1827 assertEquals(sentinel, value);
1828 return new goog.Promise(function(r) { resolveB = r; });
1829 }).then(function(value) {
1830 assertEquals(3, value);
1831 calls.push('unresolvedChild');
1832 });
1833
1834 resolveA(sentinel);
1835 assertArrayEquals(
1836 'Calls must not be resolved until the clock ticks.', [], calls);
1837
1838 mockClock.tick();
1839 assertArrayEquals(
1840 'All resolved Promises should execute in the same timestep.',
1841 ['then', 'fulfilledChild', 'rejectedChild'], calls);
1842
1843 resolveB(3);
1844 assertArrayEquals(
1845 'New calls must not resolve until the clock ticks.',
1846 ['then', 'fulfilledChild', 'rejectedChild'], calls);
1847
1848 mockClock.tick();
1849 assertArrayEquals(
1850 'All callbacks should have executed.',
1851 ['then', 'fulfilledChild', 'rejectedChild', 'unresolvedChild'], calls);
1852 }
1853
1854
1855 function testHandledRejection() {
1856 mockClock.install();
1857 goog.Promise.reject(sentinel).then(shouldNotCall, function(reason) {});
1858
1859 mockClock.tick();
1860 assertEquals(0, unhandledRejections.getCallCount());
1861 }
1862
1863
1864 function testThenVoidHandledRejection() {
1865 mockClock.install();
1866 goog.Promise.reject(sentinel).thenVoid(shouldNotCall, function(reason) {});
1867
1868 mockClock.tick();
1869 assertEquals(0, unhandledRejections.getCallCount());
1870 }
1871
1872
1873 function testUnhandledRejection1() {
1874 mockClock.install();
1875 goog.Promise.reject(sentinel);
1876
1877 mockClock.tick();
1878 assertEquals(1, unhandledRejections.getCallCount());
1879 var rejectionCall = unhandledRejections.popLastCall();
1880 assertArrayEquals([sentinel], rejectionCall.getArguments());
1881 assertEquals(goog.global, rejectionCall.getThis());
1882 }
1883
1884
1885 function testUnhandledRejection2() {
1886 mockClock.install();
1887 goog.Promise.reject(sentinel).then(shouldNotCall);
1888
1889 mockClock.tick();
1890 assertEquals(1, unhandledRejections.getCallCount());
1891 var rejectionCall = unhandledRejections.popLastCall();
1892 assertArrayEquals([sentinel], rejectionCall.getArguments());
1893 assertEquals(goog.global, rejectionCall.getThis());
1894 }
1895
1896
1897 function testThenVoidUnhandledRejection() {
1898 mockClock.install();
1899 goog.Promise.reject(sentinel).thenVoid(shouldNotCall);
1900
1901 mockClock.tick();
1902 assertEquals(1, unhandledRejections.getCallCount());
1903 var rejectionCall = unhandledRejections.popLastCall();
1904 assertArrayEquals([sentinel], rejectionCall.getArguments());
1905 assertEquals(goog.global, rejectionCall.getThis());
1906 }
1907
1908
1909 function testUnhandledRejection() {
1910 var resolver = goog.Promise.withResolver();
1911
1912 goog.Promise.setUnhandledRejectionHandler(function(err) {
1913 assertEquals(sentinel, err);
1914 resolver.resolve();
1915 });
1916 goog.Promise.reject(sentinel);
1917
1918 return resolver.promise;
1919 }
1920
1921
1922 function testUnhandledThrow() {
1923 var resolver = goog.Promise.withResolver();
1924
1925 goog.Promise.setUnhandledRejectionHandler(function(err) {
1926 assertEquals(sentinel, err);
1927 resolver.resolve();
1928 });
1929 goog.Promise.resolve().then(function() { throw sentinel; });
1930
1931 return resolver.promise;
1932 }
1933
1934
1935 function testThenVoidUnhandledThrow() {
1936 var resolver = goog.Promise.withResolver();
1937
1938 goog.Promise.setUnhandledRejectionHandler(function(error) {
1939 assertEquals(sentinel, error);
1940 resolver.resolve();
1941 });
1942
1943 goog.Promise.resolve().thenVoid(function() { throw sentinel; });
1944
1945 return resolver.promise;
1946 }
1947
1948
1949 function testUnhandledBlockingRejection() {
1950 mockClock.install();
1951 var blocker = goog.Promise.reject(sentinel);
1952 goog.Promise.resolve(blocker);
1953
1954 mockClock.tick();
1955 assertEquals(1, unhandledRejections.getCallCount());
1956 var rejectionCall = unhandledRejections.popLastCall();
1957 assertArrayEquals([sentinel], rejectionCall.getArguments());
1958 assertEquals(goog.global, rejectionCall.getThis());
1959 }
1960
1961
1962 function testUnhandledRejectionAfterThenAlways() {
1963 mockClock.install();
1964 var resolver = goog.Promise.withResolver();
1965 resolver.promise.thenAlways(function() {});
1966 resolver.reject(sentinel);
1967
1968 mockClock.tick();
1969 assertEquals(1, unhandledRejections.getCallCount());
1970 var rejectionCall = unhandledRejections.popLastCall();
1971 assertArrayEquals([sentinel], rejectionCall.getArguments());
1972 assertEquals(goog.global, rejectionCall.getThis());
1973 }
1974
1975
1976 function testHandledBlockingRejection() {
1977 mockClock.install();
1978 var blocker = goog.Promise.reject(sentinel);
1979 goog.Promise.resolve(blocker).then(shouldNotCall, function(reason) {});
1980
1981 mockClock.tick();
1982 assertEquals(0, unhandledRejections.getCallCount());
1983 }
1984
1985
1986 function testThenVoidHandledBlockingRejection() {
1987 var shouldCall = goog.testing.recordFunction();
1988
1989 mockClock.install();
1990 var blocker = goog.Promise.reject(sentinel);
1991 goog.Promise.resolve(blocker).thenVoid(shouldNotCall, shouldCall);
1992
1993 mockClock.tick();
1994 assertEquals(0, unhandledRejections.getCallCount());
1995 assertEquals(1, shouldCall.getCallCount());
1996 }
1997
1998
1999 function testUnhandledRejectionWithTimeout() {
2000 mockClock.install();
2001 stubs.replace(goog.Promise, 'UNHANDLED_REJECTION_DELAY', 200);
2002 goog.Promise.reject(sentinel);
2003
2004 mockClock.tick(199);
2005 assertEquals(0, unhandledRejections.getCallCount());
2006
2007 mockClock.tick(1);
2008 assertEquals(1, unhandledRejections.getCallCount());
2009 }
2010
2011
2012 function testHandledRejectionWithTimeout() {
2013 mockClock.install();
2014 stubs.replace(goog.Promise, 'UNHANDLED_REJECTION_DELAY', 200);
2015 var p = goog.Promise.reject(sentinel);
2016
2017 mockClock.tick(199);
2018 p.then(shouldNotCall, function(reason) {});
2019
2020 mockClock.tick(1);
2021 assertEquals(0, unhandledRejections.getCallCount());
2022 }
2023
2024
2025 function testUnhandledRejectionDisabled() {
2026 mockClock.install();
2027 stubs.replace(goog.Promise, 'UNHANDLED_REJECTION_DELAY', -1);
2028 goog.Promise.reject(sentinel);
2029
2030 mockClock.tick();
2031 assertEquals(0, unhandledRejections.getCallCount());
2032 }
2033
2034
2035 function testThenableInterface() {
2036 var promise = new goog.Promise(function(resolve, reject) {});
2037 assertTrue(goog.Thenable.isImplementedBy(promise));
2038
2039 assertFalse(goog.Thenable.isImplementedBy({}));
2040 assertFalse(goog.Thenable.isImplementedBy('string'));
2041 assertFalse(goog.Thenable.isImplementedBy(1));
2042 assertFalse(goog.Thenable.isImplementedBy({then: function() {}}));
2043
2044 function T() {}
2045 T.prototype.then = function(opt_a, opt_b, opt_c) {};
2046 goog.Thenable.addImplementation(T);
2047 assertTrue(goog.Thenable.isImplementedBy(new T));
2048
2049 // Test COMPILED code path.
2050 try {
2051 COMPILED = true;
2052 function C() {}
2053 C.prototype.then = function(opt_a, opt_b, opt_c) {};
2054 goog.Thenable.addImplementation(C);
2055 assertTrue(goog.Thenable.isImplementedBy(new C));
2056 } finally {
2057 COMPILED = false;
2058 }
2059 }
2060
2061
2062 function testCreateWithResolver_Resolved() {
2063 mockClock.install();
2064 var timesCalled = 0;
2065
2066 var resolver = goog.Promise.withResolver();
2067
2068 resolver.promise.then(function(value) {
2069 timesCalled++;
2070 assertEquals(sentinel, value);
2071 }, fail);
2072
2073 assertEquals(
2074 'then() must return before callbacks are invoked.', 0, timesCalled);
2075
2076 mockClock.tick();
2077
2078 assertEquals(
2079 'promise is not resolved until resolver is invoked.', 0, timesCalled);
2080
2081 resolver.resolve(sentinel);
2082
2083 assertEquals('resolution is delayed until the next tick', 0, timesCalled);
2084
2085 mockClock.tick();
2086
2087 assertEquals('onFulfilled must be called exactly once.', 1, timesCalled);
2088 }
2089
2090
2091 function testCreateWithResolver_Rejected() {
2092 mockClock.install();
2093 var timesCalled = 0;
2094
2095 var resolver = goog.Promise.withResolver();
2096
2097 resolver.promise.then(fail, function(reason) {
2098 timesCalled++;
2099 assertEquals(sentinel, reason);
2100 });
2101
2102 assertEquals(
2103 'then() must return before callbacks are invoked.', 0, timesCalled);
2104
2105 mockClock.tick();
2106
2107 assertEquals(
2108 'promise is not resolved until resolver is invoked.', 0, timesCalled);
2109
2110 resolver.reject(sentinel);
2111
2112 assertEquals('resolution is delayed until the next tick', 0, timesCalled);
2113
2114 mockClock.tick();
2115
2116 assertEquals('onFulfilled must be called exactly once.', 1, timesCalled);
2117 }
2118
2119
2120 function testLinksBetweenParentsAndChildrenAreCutOnResolve() {
2121 mockClock.install();
2122 var parentResolver = goog.Promise.withResolver();
2123 var parent = parentResolver.promise;
2124 var child = parent.then(function() {});
2125 assertNotNull(child.parent_);
2126 assertEquals(null, parent.callbackEntries_.next);
2127 parentResolver.resolve();
2128 mockClock.tick();
2129 assertNull(child.parent_);
2130 assertEquals(null, parent.callbackEntries_);
2131 }
2132
2133
2134 function testLinksBetweenParentsAndChildrenAreCutWithUnresolvedChild() {
2135 mockClock.install();
2136 var parentResolver = goog.Promise.withResolver();
2137 var parent = parentResolver.promise;
2138 var child = parent.then(function() {
2139 // Will never resolve.
2140 return new goog.Promise(function() {});
2141 });
2142 assertNotNull(child.parent_);
2143 assertNull(parent.callbackEntries_.next);
2144 parentResolver.resolve();
2145 mockClock.tick();
2146 assertNull(child.parent_);
2147 assertEquals(null, parent.callbackEntries_);
2148 }
2149
2150
2151 function testLinksBetweenParentsAndChildrenAreCutOnCancel() {
2152 mockClock.install();
2153 var parent = new goog.Promise(function() {});
2154 var child = parent.then(function() {});
2155 var grandChild = child.then(function() {});
2156 assertEquals(null, child.callbackEntries_.next);
2157 assertNotNull(child.parent_);
2158 assertEquals(null, parent.callbackEntries_.next);
2159 parent.cancel();
2160 mockClock.tick();
2161 assertNull(child.parent_);
2162 assertNull(grandChild.parent_);
2163 assertEquals(null, parent.callbackEntries_);
2164 assertEquals(null, child.callbackEntries_);
2165 }