@yaks/testing 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +427 -2
  3. package/_dist/assert.d.ts +40 -0
  4. package/_dist/assert.d.ts.map +1 -0
  5. package/_dist/choose.d.ts +39 -0
  6. package/_dist/choose.d.ts.map +1 -0
  7. package/_dist/clock.d.ts +8 -0
  8. package/_dist/clock.d.ts.map +1 -0
  9. package/_dist/deps.d.ts +113 -0
  10. package/_dist/deps.d.ts.map +1 -0
  11. package/_dist/examples.d.ts +69 -0
  12. package/_dist/examples.d.ts.map +1 -0
  13. package/_dist/find.d.ts +23 -0
  14. package/_dist/find.d.ts.map +1 -0
  15. package/_dist/kept.d.ts +27 -0
  16. package/_dist/kept.d.ts.map +1 -0
  17. package/_dist/lend.d.ts +15 -0
  18. package/_dist/lend.d.ts.map +1 -0
  19. package/_dist/main.d.ts +2 -0
  20. package/_dist/main.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +45 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/names.d.ts +31 -0
  24. package/_dist/names.d.ts.map +1 -0
  25. package/_dist/own.d.ts +25 -0
  26. package/_dist/own.d.ts.map +1 -0
  27. package/_dist/reads.d.ts +8 -0
  28. package/_dist/reads.d.ts.map +1 -0
  29. package/_dist/suite.d.ts +82 -0
  30. package/_dist/suite.d.ts.map +1 -0
  31. package/_dist/typist.d.ts +24 -0
  32. package/_dist/typist.d.ts.map +1 -0
  33. package/_dist/wait.d.ts +21 -0
  34. package/_dist/wait.d.ts.map +1 -0
  35. package/assert.js +114 -0
  36. package/assert.js.map +1 -0
  37. package/assert.ts +143 -0
  38. package/choose.js +197 -0
  39. package/choose.js.map +1 -0
  40. package/choose.ts +327 -0
  41. package/clock.js +45 -0
  42. package/clock.js.map +1 -0
  43. package/clock.ts +60 -0
  44. package/deno.json +1 -0
  45. package/deps.js +868 -0
  46. package/deps.js.map +1 -0
  47. package/deps.ts +1004 -0
  48. package/drive.js +43 -0
  49. package/drive.js.map +1 -0
  50. package/drive.ts +41 -0
  51. package/examples.js +279 -0
  52. package/examples.js.map +1 -0
  53. package/examples.ts +380 -0
  54. package/find.js +86 -0
  55. package/find.js.map +1 -0
  56. package/find.ts +102 -0
  57. package/kept.js +128 -0
  58. package/kept.js.map +1 -0
  59. package/kept.ts +146 -0
  60. package/lend.js +30 -0
  61. package/lend.js.map +1 -0
  62. package/lend.ts +31 -0
  63. package/load.js +106 -0
  64. package/load.js.map +1 -0
  65. package/load.ts +139 -0
  66. package/main.js +214 -0
  67. package/main.js.map +1 -0
  68. package/main.ts +217 -0
  69. package/mod.js +45 -0
  70. package/mod.js.map +1 -0
  71. package/mod.ts +55 -0
  72. package/names.js +209 -0
  73. package/names.js.map +1 -0
  74. package/names.ts +204 -0
  75. package/own.js +109 -0
  76. package/own.js.map +1 -0
  77. package/own.ts +136 -0
  78. package/package.json +56 -4
  79. package/reads.js +88 -0
  80. package/reads.js.map +1 -0
  81. package/reads.ts +98 -0
  82. package/run.js +306 -0
  83. package/run.js.map +1 -0
  84. package/run.ts +405 -0
  85. package/suite.js +191 -0
  86. package/suite.js.map +1 -0
  87. package/suite.ts +224 -0
  88. package/typist.js +74 -0
  89. package/typist.js.map +1 -0
  90. package/typist.ts +79 -0
  91. package/wait.js +34 -0
  92. package/wait.js.map +1 -0
  93. package/wait.ts +60 -0
package/suite.ts ADDED
@@ -0,0 +1,224 @@
1
+ // The words a test module declares its tests in, and the list they land in.
2
+ // A module only declares: the runner (./main.ts) collects what every module
3
+ // it loads declares and runs the lot in one runtime. A module loaded by
4
+ // anything else, `deno test` or an editor, hands each test to Deno.test.
5
+ import * as assertions from './assert.js'
6
+
7
+ /** A test's tags, which a run is filtered by, and whether it is skipped. */
8
+ export type Options = { tags?: string[]; skip?: boolean }
9
+
10
+ /** One declared test. `file` is the module the runner was loading. */
11
+ export type Test = {
12
+ name: string
13
+ body: () => unknown
14
+ tags: string[]
15
+ skip: boolean
16
+ file: string
17
+ }
18
+
19
+ let tests: Test[] | undefined
20
+ let file = ''
21
+ // Whether a stack has been read since the module now loading was named.
22
+ let mapped = false
23
+
24
+ /** Starts collecting: every test declared from now on lands in the list
25
+ * returned, instead of going to Deno.test. */
26
+ export let collect = (): Test[] => tests = []
27
+
28
+ /** Names the module whose declarations follow, and opens its scope
29
+ * (`afterAll`). */
30
+ export let from = (path: string) => {
31
+ file = path
32
+ mapped = false
33
+ leaving = tests ? [] : undefined
34
+ }
35
+
36
+ /**
37
+ * Declares a test: a name, a body that throws or rejects to fail, and the
38
+ * tags a run can pick it by.
39
+ *
40
+ * ```ts ignore
41
+ * test('two and two', () => equal(2 + 2, 4))
42
+ * test('the whole shop', async () => ok(await shop()), { tags: ['kernel'] })
43
+ * ```
44
+ */
45
+ export let test = (
46
+ name: string,
47
+ body: () => unknown,
48
+ { tags = [], skip = false }: Options = {},
49
+ ): void => {
50
+ if (tests) {
51
+ // The first stack read that holds a module's frame reads the module's
52
+ // source map, half a millisecond, once. A module declares from its own
53
+ // frame, so the map is read here, in its load, rather than by whichever
54
+ // of its tests first reports an error.
55
+ mapped ||= !!Error().stack
56
+ tests.push({ name, body, tags, skip, file })
57
+ } else {
58
+ globalThis.Deno?.test({ name, ignore: skip, fn: () => closing(body) })
59
+ }
60
+ }
61
+
62
+ // What the running test asked to have done once it ends (`cleanup`), and
63
+ // what the file the runner loaded last asked to have done once its tests
64
+ // have run (`afterAll`).
65
+ let ending: (() => unknown)[] | undefined
66
+ let leaving: (() => unknown)[] | undefined
67
+
68
+ /**
69
+ * Asks for `done` once the running test ends, before its time is taken, so
70
+ * a test pays for closing what it opened and leaves nothing running into
71
+ * the next one. Outside a test, it is the file's (`afterAll`). Outside the
72
+ * runner and any test it does nothing, and answers false.
73
+ *
74
+ * ```ts ignore
75
+ * let fixture = () => {
76
+ * let db = open()
77
+ * cleanup(() => db.close())
78
+ * return db
79
+ * }
80
+ * ```
81
+ */
82
+ export let cleanup = (done: () => unknown): boolean => {
83
+ let scope = ending ?? leaving
84
+ scope?.push(done)
85
+ return !!scope
86
+ }
87
+
88
+ /**
89
+ * Asks for `done` once the file the runner loaded last has run its tests,
90
+ * whichever of them asks. A runtime keeps every module it loads, and what a
91
+ * module holds: a kernel a file opened for its tests would otherwise run on,
92
+ * holding every store it made, beside every file the runtime loads after.
93
+ * Outside the runner it does nothing, and answers false.
94
+ *
95
+ * ```ts ignore
96
+ * let shared: Promise<Kernel> | undefined
97
+ * let kernel = () => {
98
+ * if (!shared) afterAll(async () => (await shared)?.close())
99
+ * return shared ??= boot()
100
+ * }
101
+ * ```
102
+ */
103
+ export let afterAll = (done: () => unknown): boolean => {
104
+ leaving?.push(done)
105
+ return !!leaving
106
+ }
107
+
108
+ // What files asked the runtime to keep until it needs their memory back
109
+ // (`kept`), and the file that asked last.
110
+ let keeping: (() => unknown)[] = []
111
+ let keeper = ''
112
+
113
+ /**
114
+ * Asks for `done` once the runtime needs back the memory a fixture holds
115
+ * (./main.ts `full`), rather than once the file that made it ends: a fixture
116
+ * that costs more to make than to keep (a kernel, say) serves every file
117
+ * after it until then. Outside the runner it does nothing, and answers false.
118
+ *
119
+ * ```ts ignore
120
+ * let shared: Promise<Kernel> | undefined
121
+ * let kernel = () => {
122
+ * if (!shared) kept(async () => (await shared)?.close())
123
+ * return shared ??= boot()
124
+ * }
125
+ * ```
126
+ */
127
+ export let kept = (done: () => unknown): boolean => {
128
+ if (!tests) return false
129
+ keeping.push(done)
130
+ keeper = file
131
+ return true
132
+ }
133
+
134
+ /** What the runtime kept (`kept`), run last asked first, with the file that
135
+ * asked last; none when it keeps nothing. The runtime keeps nothing after. */
136
+ export let unkept = ():
137
+ | { file: string; body: () => Promise<void> }
138
+ | undefined => {
139
+ let asked = keeping
140
+ keeping = []
141
+ return asked.length ? { file: keeper, body: () => settle(asked) } : undefined
142
+ }
143
+
144
+ /** What the file the runner loaded last asked for with `afterAll`, run last
145
+ * asked first; none when it asked for nothing. The scope closes: the file
146
+ * asks for no more. */
147
+ export let left = (): (() => Promise<void>) | undefined => {
148
+ let asked = leaving
149
+ leaving = undefined
150
+ return asked?.length ? () => settle(asked) : undefined
151
+ }
152
+
153
+ /** Runs a test's body, then what it asked to have done once it ends, last
154
+ * asked first. A body's failure is the test's; else the first cleanup's. */
155
+ export let closing = async (body: () => unknown): Promise<void> => {
156
+ let was = ending
157
+ let asked: (() => unknown)[] = ending = []
158
+ let failed: { error: unknown } | undefined
159
+ try {
160
+ await body()
161
+ } catch (error) {
162
+ failed = { error }
163
+ } finally {
164
+ ending = was
165
+ }
166
+ await settle(asked, failed)
167
+ }
168
+
169
+ // Runs what a scope asked for, last asked first: the scope's failure, or else
170
+ // the first of theirs, is thrown once all have run.
171
+ let settle = async (
172
+ asked: (() => unknown)[],
173
+ failed?: { error: unknown },
174
+ ): Promise<void> => {
175
+ for (let done of asked.reverse()) {
176
+ try {
177
+ await done()
178
+ } catch (error) {
179
+ failed ??= { error }
180
+ }
181
+ }
182
+ if (failed) throw failed.error
183
+ }
184
+
185
+ /** Declares one clause of a suite; `it.skip` declares it skipped. */
186
+ export type It =
187
+ & ((name: string, body: () => unknown, options?: Options) => void)
188
+ & { skip: (name: string, body: () => unknown) => void }
189
+
190
+ /** What a suite's body declares with: `it`, and the assertions. */
191
+ export type Spec = typeof assertions & { it: It }
192
+
193
+ /**
194
+ * Declares a group of tests under one name, each clause named after it and
195
+ * carrying its tags. A body that throws declares a failing test instead.
196
+ *
197
+ * ```ts ignore
198
+ * suite('sum', ({ it, equal }) => {
199
+ * it('adds', () => equal(sum([1, 2]), 3))
200
+ * it('of nothing is zero', () => equal(sum([]), 0))
201
+ * })
202
+ * ```
203
+ */
204
+ export let suite = (
205
+ name: string,
206
+ body: (spec: Spec) => void,
207
+ options: Options = {},
208
+ ): void => {
209
+ let it: It = Object.assign(
210
+ (what: string, fn: () => unknown, more: Options = {}) =>
211
+ test(`${name} › ${what}`, fn, {
212
+ tags: [...options.tags ?? [], ...more.tags ?? []],
213
+ skip: options.skip || more.skip,
214
+ }),
215
+ { skip: (what: string, fn: () => unknown) => it(what, fn, { skip: true }) },
216
+ )
217
+ try {
218
+ body({ ...assertions, it })
219
+ } catch (error) {
220
+ test(`${name} › declares its tests`, () => {
221
+ throw error
222
+ }, options)
223
+ }
224
+ }
package/typist.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A text field kept the way a browser keeps one, on a DOM that keeps none
3
+ * (linkedom): a value a script puts in moves the caret to the end, and a
4
+ * person's typing goes in at the caret, replacing what is selected, and fires
5
+ * `input`. A bug that moves the caret shows here as it does in a browser.
6
+ *
7
+ * ```ts ignore
8
+ * let t = typist(textarea)
9
+ * t.at(4)
10
+ * t.type(' me')
11
+ * equal([textarea.value, textarea.selectionStart], ['Find me the recipe', 7])
12
+ * ```
13
+ *
14
+ * @module
15
+ */ /** A person at `el`: `at` puts the caret (or selects to `to`), `type` types
16
+ * at it, and `compose` types as an input method does, `end` closing it. */ export let typist = (el)=>{
17
+ let text = el.value;
18
+ let from = text.length, to = text.length;
19
+ Object.defineProperties(el, {
20
+ value: {
21
+ configurable: true,
22
+ get: ()=>text,
23
+ set: (v)=>{
24
+ text = String(v).replace(/\r\n?/g, '\n');
25
+ from = to = text.length;
26
+ }
27
+ },
28
+ selectionStart: {
29
+ configurable: true,
30
+ get: ()=>from
31
+ },
32
+ selectionEnd: {
33
+ configurable: true,
34
+ get: ()=>to
35
+ },
36
+ selectionDirection: {
37
+ configurable: true,
38
+ get: ()=>'none'
39
+ },
40
+ setSelectionRange: {
41
+ configurable: true,
42
+ value: (a, b)=>{
43
+ from = a;
44
+ to = b;
45
+ }
46
+ }
47
+ });
48
+ let fire = (type)=>{
49
+ let E = el.ownerDocument.defaultView?.Event ?? Event;
50
+ el.dispatchEvent(new E(type, {
51
+ bubbles: true
52
+ }));
53
+ };
54
+ let put = (typed)=>{
55
+ text = text.slice(0, from) + typed + text.slice(to);
56
+ from = to = from + typed.length;
57
+ fire('input');
58
+ };
59
+ return {
60
+ at: (a, b = a)=>{
61
+ from = a;
62
+ to = b;
63
+ },
64
+ type: (typed)=>{
65
+ for (let c of typed)put(c);
66
+ },
67
+ compose: (typed)=>{
68
+ fire('compositionstart');
69
+ put(typed);
70
+ },
71
+ end: ()=>fire('compositionend')
72
+ };
73
+ };
74
+ //# sourceMappingURL=typist.js.map
package/typist.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typist.js","sources":["./typist.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;CAcC,GAgBD;yEACyE,GACzE,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,OAAO,GAAG,KAAK;EACnB,IAAI,OAAO,KAAK,MAAM,EAAE,KAAK,KAAK,MAAM;EACxC,OAAO,gBAAgB,CAAC,IAAI;IAC1B,OAAO;MACL,cAAc;MACd,KAAK,IAAM;MACX,KAAK,CAAC;QACJ,OAAO,OAAO,GAAG,OAAO,CAAC,UAAU;QACnC,OAAO,KAAK,KAAK,MAAM;MACzB;IACF;IACA,gBAAgB;MAAE,cAAc;MAAM,KAAK,IAAM;IAAK;IACtD,cAAc;MAAE,cAAc;MAAM,KAAK,IAAM;IAAG;IAClD,oBAAoB;MAAE,cAAc;MAAM,KAAK,IAAM;IAAO;IAC5D,mBAAmB;MACjB,cAAc;MACd,OAAO,CAAC,GAAW;QACjB,OAAO;QACP,KAAK;MACP;IACF;EACF;EACA,IAAI,OAAO,CAAC;IACV,IAAI,IAAI,GAAG,aAAa,CAAC,WAAW,EAAE,SAAS;IAC/C,GAAG,aAAa,CAAC,IAAI,EAAE,MAAM;MAAE,SAAS;IAAK;EAC/C;EACA,IAAI,MAAM,CAAC;IACT,OAAO,KAAK,KAAK,CAAC,GAAG,QAAQ,QAAQ,KAAK,KAAK,CAAC;IAChD,OAAO,KAAK,OAAO,MAAM,MAAM;IAC/B,KAAK;EACP;EACA,OAAO;IACL,IAAI,CAAC,GAAW,IAAI,CAAC;MACnB,OAAO;MACP,KAAK;IACP;IACA,MAAM,CAAC;MACL,KAAK,IAAI,KAAK,MAAO,IAAI;IAC3B;IACA,SAAS,CAAC;MACR,KAAK;MACL,IAAI;IACN;IACA,KAAK,IAAM,KAAK;EAClB;AACF,EAAC"}
package/typist.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A text field kept the way a browser keeps one, on a DOM that keeps none
3
+ * (linkedom): a value a script puts in moves the caret to the end, and a
4
+ * person's typing goes in at the caret, replacing what is selected, and fires
5
+ * `input`. A bug that moves the caret shows here as it does in a browser.
6
+ *
7
+ * ```ts ignore
8
+ * let t = typist(textarea)
9
+ * t.at(4)
10
+ * t.type(' me')
11
+ * equal([textarea.value, textarea.selectionStart], ['Find me the recipe', 7])
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+
17
+ type Typed = HTMLInputElement | HTMLTextAreaElement
18
+
19
+ /** A person at a field. */
20
+ export type Typist = {
21
+ /** put the caret at `a`, or select from `a` to `b` */
22
+ at: (a: number, b?: number) => void
23
+ /** type `typed` at the caret, a character at a time */
24
+ type: (typed: string) => void
25
+ /** type `typed` at once as an input method composes it */
26
+ compose: (typed: string) => void
27
+ /** end the composition */
28
+ end: () => void
29
+ }
30
+
31
+ /** A person at `el`: `at` puts the caret (or selects to `to`), `type` types
32
+ * at it, and `compose` types as an input method does, `end` closing it. */
33
+ export let typist = (el: Typed): Typist => {
34
+ let text = el.value
35
+ let from = text.length, to = text.length
36
+ Object.defineProperties(el, {
37
+ value: {
38
+ configurable: true,
39
+ get: () => text,
40
+ set: (v: string) => {
41
+ text = String(v).replace(/\r\n?/g, '\n')
42
+ from = to = text.length
43
+ },
44
+ },
45
+ selectionStart: { configurable: true, get: () => from },
46
+ selectionEnd: { configurable: true, get: () => to },
47
+ selectionDirection: { configurable: true, get: () => 'none' },
48
+ setSelectionRange: {
49
+ configurable: true,
50
+ value: (a: number, b: number) => {
51
+ from = a
52
+ to = b
53
+ },
54
+ },
55
+ })
56
+ let fire = (type: string) => {
57
+ let E = el.ownerDocument.defaultView?.Event ?? Event
58
+ el.dispatchEvent(new E(type, { bubbles: true }))
59
+ }
60
+ let put = (typed: string) => {
61
+ text = text.slice(0, from) + typed + text.slice(to)
62
+ from = to = from + typed.length
63
+ fire('input')
64
+ }
65
+ return {
66
+ at: (a: number, b = a) => {
67
+ from = a
68
+ to = b
69
+ },
70
+ type: (typed: string) => {
71
+ for (let c of typed) put(c)
72
+ },
73
+ compose: (typed: string) => {
74
+ fire('compositionstart')
75
+ put(typed)
76
+ },
77
+ end: () => fire('compositionend'),
78
+ }
79
+ }
package/wait.js ADDED
@@ -0,0 +1,34 @@
1
+ import * as system from "@yaks/process/system";
2
+ import { own } from "./own.js";
3
+ /** One macrotask yield: queued timers and microtasks flush, no span passes. */ export let tick = ()=>new Promise((go)=>setTimeout(go, 0));
4
+ // The clock `until` keeps unless told: this runtime's own time and that of
5
+ // every process it started, and the runtime's timers.
6
+ let mine = ()=>({
7
+ now: own(system.pid, {
8
+ time: ()=>Date.now()
9
+ }),
10
+ after: (ms, callback)=>{
11
+ let timer = setTimeout(callback, ms);
12
+ return ()=>clearTimeout(timer);
13
+ }
14
+ });
15
+ /**
16
+ * Wait for a fact to become true, polling instead of guessing a duration. The
17
+ * timeout only exists to fail instead of hanging; the fact's value comes back.
18
+ *
19
+ * ```ts
20
+ * let n = 0
21
+ * await until(() => ++n == 3) // true
22
+ * ```
23
+ */ export let until = async (fact, { timeout = 2000, poll = 5, label = 'it', clock = mine() } = {})=>{
24
+ let deadline = clock.now() + timeout;
25
+ while(true){
26
+ let v = await fact();
27
+ if (v) return v;
28
+ // A delayed poll may resume after the fact settled and the deadline.
29
+ if (clock.now() >= deadline) break;
30
+ await new Promise((go)=>clock.after(poll, go));
31
+ }
32
+ throw new Error(`until: timed out after ${timeout}ms waiting for ${typeof label == 'function' ? label() : label}`);
33
+ };
34
+ //# sourceMappingURL=wait.js.map
package/wait.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wait.js","sources":["./wait.ts"],"names":[],"mappings":"AAAA,YAAY,wCAA6C;AAOzD,SAAS,GAAG,mBAAkB;AAE9B,6EAA6E,GAC7E,OAAO,IAAI,OAAO,IAAqB,IAAI,QAAQ,CAAC,KAAO,WAAW,IAAI,IAAG;AAa7E,2EAA2E;AAC3E,sDAAsD;AACtD,IAAI,OAAO,IAAoC,CAAC;IAC9C,KAAK,IAAI,OAAO,GAAG,EAAE;MAAE,MAAM,IAAM,KAAK,GAAG;IAAG;IAC9C,OAAO,CAAC,IAAI;MACV,IAAI,QAAQ,WAAW,UAAU;MACjC,OAAO,IAAM,aAAa;IAC5B;EACF,CAAC;AAED;;;;;;;;CAQC,GACD,OAAO,IAAI,QAAQ,OACjB,MACA,EAAE,UAAU,IAAI,EAAE,OAAO,CAAC,EAAE,QAAQ,IAAI,EAAE,QAAQ,MAAM,EAAQ,GAAG,CAAC,CAAC;EAErE,IAAI,WAAW,MAAM,GAAG,KAAK;EAC7B,MAAO,KAAM;IACX,IAAI,IAAI,MAAM;IACd,IAAI,GAAG,OAAO;IACd,qEAAqE;IACrE,IAAI,MAAM,GAAG,MAAM,UAAU;IAC7B,MAAM,IAAI,QAAc,CAAC,KAAO,MAAM,KAAK,CAAC,MAAM;EACpD;EACA,MAAM,IAAI,MACR,CAAC,uBAAuB,EAAE,QAAQ,eAAe,EAC/C,OAAO,SAAS,aAAa,UAAU,OACvC;AAEN,EAAC"}
package/wait.ts ADDED
@@ -0,0 +1,60 @@
1
+ import * as system from '@yaks/process/system'
2
+ // The tests' one sanctioned wait. A test never sleeps a fixed span: it yields
3
+ // with `tick` and waits on a fact with `until`, both deterministic, so nothing
4
+ // pads for a settle that a loaded box would stretch past the pad. Its timeout
5
+ // counts the test's own time (./own.ts), so a busy box times out no wait that
6
+ // has not hung.
7
+ import type { Clock } from './clock.ts'
8
+ import { own } from './own.js'
9
+
10
+ /** One macrotask yield: queued timers and microtasks flush, no span passes. */
11
+ export let tick = (): Promise<void> => new Promise((go) => setTimeout(go, 0))
12
+
13
+ /** How long `until` waits, how often it looks, what it names on a timeout
14
+ * (a string, or a thunk resolved late so it can name live state), and the
15
+ * clock it keeps both by: the test's own time and the runtime's timers,
16
+ * unless a test hands it one (`clock()`). */
17
+ export type Wait = {
18
+ timeout?: number
19
+ poll?: number
20
+ label?: string | (() => string)
21
+ clock?: Pick<Clock, 'now' | 'after'>
22
+ }
23
+
24
+ // The clock `until` keeps unless told: this runtime's own time and that of
25
+ // every process it started, and the runtime's timers.
26
+ let mine = (): Pick<Clock, 'now' | 'after'> => ({
27
+ now: own(system.pid, { time: () => Date.now() }),
28
+ after: (ms, callback) => {
29
+ let timer = setTimeout(callback, ms)
30
+ return () => clearTimeout(timer)
31
+ },
32
+ })
33
+
34
+ /**
35
+ * Wait for a fact to become true, polling instead of guessing a duration. The
36
+ * timeout only exists to fail instead of hanging; the fact's value comes back.
37
+ *
38
+ * ```ts
39
+ * let n = 0
40
+ * await until(() => ++n == 3) // true
41
+ * ```
42
+ */
43
+ export let until = async <T>(
44
+ fact: () => T | Promise<T>,
45
+ { timeout = 2000, poll = 5, label = 'it', clock = mine() }: Wait = {},
46
+ ): Promise<NonNullable<T>> => {
47
+ let deadline = clock.now() + timeout
48
+ while (true) {
49
+ let v = await fact()
50
+ if (v) return v
51
+ // A delayed poll may resume after the fact settled and the deadline.
52
+ if (clock.now() >= deadline) break
53
+ await new Promise<void>((go) => clock.after(poll, go))
54
+ }
55
+ throw new Error(
56
+ `until: timed out after ${timeout}ms waiting for ${
57
+ typeof label == 'function' ? label() : label
58
+ }`,
59
+ )
60
+ }