Promise.withResolvers.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. describe("errors", () => {
  2. test("this value must be a constructor", () => {
  3. expect(() => {
  4. Promise.withResolvers.call(Symbol.hasInstance);
  5. }).toThrowWithMessage(TypeError, "Symbol(Symbol.hasInstance) is not a constructor");
  6. });
  7. });
  8. describe("normal behavior", () => {
  9. test("length is 0", () => {
  10. expect(Promise.withResolvers).toHaveLength(0);
  11. });
  12. test("returned promise is a Promise", () => {
  13. const { promise, resolve, reject } = Promise.withResolvers();
  14. expect(promise).toBeInstanceOf(Promise);
  15. });
  16. test("returned resolve/reject are unary functions", () => {
  17. const { promise, resolve, reject } = Promise.withResolvers();
  18. expect(resolve).toBeInstanceOf(Function);
  19. expect(resolve).toHaveLength(1);
  20. expect(reject).toBeInstanceOf(Function);
  21. expect(reject).toHaveLength(1);
  22. });
  23. test("returned promise can be resolved", () => {
  24. const { promise, resolve, reject } = Promise.withResolvers();
  25. let fulfillmentValue = null;
  26. promise.then(value => {
  27. fulfillmentValue = value;
  28. });
  29. resolve("Some value");
  30. runQueuedPromiseJobs();
  31. expect(fulfillmentValue).toBe("Some value");
  32. });
  33. test("returned promise can be rejected", () => {
  34. const { promise, resolve, reject } = Promise.withResolvers();
  35. let rejectionReason = null;
  36. promise.catch(value => {
  37. rejectionReason = value;
  38. });
  39. reject("Some value");
  40. runQueuedPromiseJobs();
  41. expect(rejectionReason).toBe("Some value");
  42. });
  43. });