|
| 1 | +import { afterEach, beforeEach, expect, test } from "bun:test" |
| 2 | + |
| 3 | +const native = { groupBy: Map.groupBy, withResolvers: Promise.withResolvers, try: Promise.try } |
| 4 | + |
| 5 | +const maps: Partial<typeof Map> = Map |
| 6 | + |
| 7 | +const promises: Partial<typeof Promise> = Promise |
| 8 | + |
| 9 | +beforeEach(async () => { |
| 10 | + delete maps.groupBy |
| 11 | + delete promises.withResolvers |
| 12 | + delete promises.try |
| 13 | + await import(`./polyfills?${Math.random()}`) |
| 14 | +}) |
| 15 | + |
| 16 | +afterEach(() => { |
| 17 | + Map.groupBy = native.groupBy |
| 18 | + Promise.withResolvers = native.withResolvers |
| 19 | + Promise.try = native.try |
| 20 | +}) |
| 21 | + |
| 22 | +test("Map.groupBy keeps first-seen key order and passes the index", () => { |
| 23 | + const groups = Map.groupBy([1, 2, 3, 4, 5], (n) => (n % 2 ? "odd" : "even")) |
| 24 | + expect([...groups]).toEqual([ |
| 25 | + ["odd", [1, 3, 5]], |
| 26 | + ["even", [2, 4]], |
| 27 | + ]) |
| 28 | + expect([...Map.groupBy(["a", "b"], (_, index) => index).keys()]).toEqual([0, 1]) |
| 29 | +}) |
| 30 | + |
| 31 | +test("Promise.withResolvers settles from outside", async () => { |
| 32 | + const resolved = Promise.withResolvers<number>() |
| 33 | + resolved.resolve(1) |
| 34 | + expect(await resolved.promise).toBe(1) |
| 35 | + |
| 36 | + const rejected = Promise.withResolvers<number>() |
| 37 | + rejected.reject(new Error("no")) |
| 38 | + |
| 39 | + await expect(rejected.promise).rejects.toThrow("no") |
| 40 | +}) |
| 41 | + |
| 42 | +test("Promise.try runs synchronously and isolates a throw", async () => { |
| 43 | + let ran = false |
| 44 | + |
| 45 | + const value = Promise.try(() => { |
| 46 | + ran = true |
| 47 | + |
| 48 | + return 2 |
| 49 | + }) |
| 50 | + |
| 51 | + expect(ran).toBe(true) |
| 52 | + expect(await value).toBe(2) |
| 53 | + |
| 54 | + expect(await Promise.try((a: number, b: number) => a + b, 1, 2)).toBe(3) |
| 55 | + |
| 56 | + await expect( |
| 57 | + Promise.try(() => { |
| 58 | + throw new Error("boom") |
| 59 | + }), |
| 60 | + ).rejects.toThrow("boom") |
| 61 | +}) |
0 commit comments