subclass.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. describe('Support user subclassing of Promise', function () {
  2. 'use strict';
  3. it('should work if you do it right', function (done) {
  4. // This is the "correct" es6-compatible way.
  5. // (Thanks, @domenic and @zloirock!)
  6. var MyPromise = function (executor) {
  7. var self = new Promise(executor);
  8. Object.setPrototypeOf(self, MyPromise.prototype);
  9. self.mine = 'yeah';
  10. return self;
  11. };
  12. if (!Object.setPrototypeOf) { return done(); } // skip test if on IE < 11
  13. Object.setPrototypeOf(MyPromise, Promise);
  14. MyPromise.prototype = Object.create(Promise.prototype, {
  15. constructor: { value: MyPromise }
  16. });
  17. // let's try it!
  18. var p1 = MyPromise.resolve(5);
  19. assert.strictEqual(p1.mine, 'yeah');
  20. p1 = p1.then(function (x) {
  21. assert.strictEqual(x, 5);
  22. });
  23. assert.strictEqual(p1.mine, 'yeah');
  24. var p2 = new MyPromise(function (r) { r(6); });
  25. assert.strictEqual(p2.mine, 'yeah');
  26. p2 = p2.then(function (x) {
  27. assert.strictEqual(x, 6);
  28. });
  29. assert.strictEqual(p2.mine, 'yeah');
  30. var p3 = MyPromise.all([p1, p2]);
  31. assert.strictEqual(p3.mine, 'yeah');
  32. p3.then(function () { done(); }, done);
  33. });
  34. it("should throw if you don't inherit at all", function () {
  35. var MyPromise = function () {};
  36. assert['throws'](function () {
  37. Promise.all.call(MyPromise, []);
  38. }, TypeError);
  39. });
  40. });