Promise.try.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. describe("errors", () => {
  2. test("this value must be a constructor", () => {
  3. expect(() => {
  4. Promise.try.call({});
  5. }).toThrowWithMessage(TypeError, "[object Object] is not a constructor");
  6. });
  7. });
  8. describe("normal behavior", () => {
  9. test("length is 1", () => {
  10. expect(Promise.try).toHaveLength(1);
  11. });
  12. test("returned promise is a Promise", () => {
  13. const fn = () => {};
  14. const promise = Promise.try(fn);
  15. expect(promise).toBeInstanceOf(Promise);
  16. });
  17. test("returned promise is resolved when function completes normally", () => {
  18. const fn = () => {};
  19. const promise = Promise.try(fn);
  20. let fulfillmentValue = null;
  21. promise.then(value => {
  22. fulfillmentValue = value;
  23. });
  24. runQueuedPromiseJobs();
  25. expect(fulfillmentValue).toBe(undefined);
  26. });
  27. test("returned promise is rejected when function throws", () => {
  28. const fn = () => {
  29. throw "error";
  30. };
  31. const promise = Promise.try(fn);
  32. let rejectionReason = null;
  33. promise.catch(value => {
  34. rejectionReason = value;
  35. });
  36. runQueuedPromiseJobs();
  37. expect(rejectionReason).toBe("error");
  38. });
  39. test("arguments are forwarded to the function", () => {
  40. const fn = (...args) => args;
  41. const promise = Promise.try(fn, "foo", 123, true);
  42. let fulfillmentValue = null;
  43. promise.then(value => {
  44. fulfillmentValue = value;
  45. });
  46. runQueuedPromiseJobs();
  47. expect(fulfillmentValue).toEqual(["foo", 123, true]);
  48. });
  49. });