@cslug/testing 0.1.0 → 0.3.0

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.
package/docs/README.md CHANGED
@@ -23,5 +23,5 @@ test('adding a todo', async () => {
23
23
  Requests go straight to the HTTP kernel (no port). `.form()` adds the CSRF token and a Referer as a browser
24
24
  would, so failed validation redirects back and `assertInvalid()` / `assertOldInput()` read the flashed errors.
25
25
 
26
- More assertions arrive with their packages: `actingAs` (auth), `assertQueued` (queue), `assertView` /
27
- `assertIsland` (vue), `assertSent` (mail). See [api.md](api.md).
26
+ Packages plug in: `actingAs`, `t.auth`, `t.tokens` (auth), `t.queue` and `t.schedule` (queue), `assertView` /
27
+ `assertIsland` (vue), `t.mail` (mail). See [api.md](api.md).
package/docs/api.md CHANGED
@@ -6,27 +6,34 @@
6
6
  |---|---|---|
7
7
  | `create` | `createApp()` from `bootstrap/app.ts` | Build the app |
8
8
  | `config` | | Overrides by dotted path |
9
- | `fakes` | `[]` | `'events'`, plus those packages register |
9
+ | `fakes` | `[]` | `'events'`, `'queue'`, `'mail'` (loaded from their package). A fake listed here is typed as present on `t` |
10
10
  | `database` | `'transaction'` | `'truncate'` or `false` |
11
11
  | `migrate` | `true` | Runs `database/migrations` once |
12
12
  | `host` | host of `app.url` | |
13
13
 
14
14
  Returns: `app`, `clock`, `resolve`, `swap`, `actingAs(user)` (for every request of the test), `get/post/put/patch/delete(path)`, `beforeRequest(hook)`,
15
- `db.count(table, where?)`, `db.find(table, id)`, `assertDatabaseHas/Missing(table, where)` (camelCase keys), and
16
- each installed fake as `t.<name>`.
15
+ `db.count(table, where?)`, `db.find(table, id)`, `assertDatabaseHas/Missing(table, where)` (camelCase keys; values
16
+ or `@cslug/database` operators: `{ remindedAt: notNull() }`), each installed fake as `t.<name>`, and:
17
+
18
+ - `auth.check()` / `auth.user()`: who the session says is signed in after the last request (@cslug/auth).
19
+ - `tokens.create(user, { abilities?, name?, expiresIn? })` → `{ plainText }` (@cslug/auth).
20
+ - `schedule.runDue()`: run the schedule entries due at `t.clock`'s time (@cslug/queue's ScheduleProvider).
17
21
 
18
22
  ## Requests (`PendingRequest`, awaited to run)
19
23
 
20
24
  Building: `header`, `headers({…})`, `withToken`, `actingAs(user)` (signed in through the session, with
21
- @cslug/auth), `json(data)`, `form(data)` (nested keys, CSRF, Referer).
25
+ @cslug/auth), `json(data)` (writes carry the session's CSRF token in `X-CSRF-Token`, as an island's `useForm`
26
+ does), `form(data)` (nested keys, CSRF, Referer).
22
27
 
23
28
  Assertions (queued, run in order): `assertStatus`, `assertOk`, `assertCreated`, `assertNoContent`,
24
29
  `assertNotFound`, `assertForbidden`, `assertUnauthorized`, `assertRedirect(to?)`, `assertJson(subset)`,
25
30
  `assertProblem(status, code)`, `assertInvalid({ field: 'part of message' })` (JSON 422 or flashed),
26
31
  `assertOldInput`, `assertSessionHas(key, value?)`, `assertSessionMissing`, `assertSee`, `assertDontSee`,
27
- `assertHeader`, `assertCookie`. `follow()` makes the GET to the redirect location with the same cookies.
32
+ `assertHeader`, `assertCookie`, `assertView(View, (props) => …)` (the page `view()` rendered for this request,
33
+ @cslug/vue), `assertIsland(name, props?)` (an island marker in the HTML; `name` with or without its folder,
34
+ `props` a deep subset). `follow()` makes the GET to the redirect location with the same cookies.
28
35
 
29
- The awaited value is a `TestResponse`: `status`, `headers`, `body()`, `json()`, `session()`.
36
+ The awaited value is a `TestResponse`: `status`, `headers`, `body()`, `json()`, `session()`, `views`, `islands()`.
30
37
 
31
38
  ## Fakes
32
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/testing",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Test kit: testApp(), HTTP and HTML assertions, database isolation, fakes, time travel.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -28,20 +28,20 @@
28
28
  "bun": ">=1.3.14"
29
29
  },
30
30
  "peerDependencies": {
31
- "@cslug/core": "0.1.0",
32
- "@cslug/validation": "0.1.0",
33
- "@cslug/http": "0.1.0",
34
- "@cslug/vue": "0.1.0",
35
- "@cslug/database": "0.1.0",
36
- "@cslug/redis": "0.1.0",
37
- "@cslug/queue": "0.1.0",
38
- "@cslug/auth": "0.1.0",
39
- "@cslug/mail": "0.1.0",
40
- "@cslug/notification": "0.1.0",
41
- "@cslug/storage": "0.1.0",
42
- "@cslug/webhook": "0.1.0",
43
- "@cslug/ai": "0.1.0",
44
- "@cslug/cli": "0.1.0"
31
+ "@cslug/core": "0.3.0",
32
+ "@cslug/validation": "0.3.0",
33
+ "@cslug/http": "0.3.0",
34
+ "@cslug/vue": "0.3.0",
35
+ "@cslug/database": "0.3.0",
36
+ "@cslug/redis": "0.3.0",
37
+ "@cslug/queue": "0.3.0",
38
+ "@cslug/auth": "0.3.0",
39
+ "@cslug/mail": "0.3.0",
40
+ "@cslug/notification": "0.3.0",
41
+ "@cslug/storage": "0.3.0",
42
+ "@cslug/webhook": "0.3.0",
43
+ "@cslug/ai": "0.3.0",
44
+ "@cslug/cli": "0.3.0"
45
45
  },
46
46
  "peerDependenciesMeta": {
47
47
  "@cslug/validation": {
package/src/fakes.ts CHANGED
@@ -14,6 +14,27 @@ export function registerFake(name: string, install: FakeInstaller): void {
14
14
  }
15
15
  export const fakeInstaller = (name: string) => installers.get(name)
16
16
 
17
+ /** Fakes of optional packages, loaded on first use (the package may not be installed). */
18
+ const lazy: Record<string, () => Promise<FakeInstaller>> = {
19
+ queue: async () => (await import('@cslug/queue')).installQueueFake,
20
+ mail: async () => (await import('@cslug/mail')).installMailFake,
21
+ storage: async () => (await import('@cslug/storage')).installStorageFake,
22
+ notify: async () => (await import('@cslug/notification')).installNotificationFake,
23
+ }
24
+
25
+ /** The installer for `name`: registered, or loaded from its package. Undefined if neither. */
26
+ export async function loadFake(name: string): Promise<FakeInstaller | undefined> {
27
+ const known = installers.get(name)
28
+ if (known || !lazy[name]) return known
29
+ try {
30
+ const install = await (lazy[name] as () => Promise<FakeInstaller>)()
31
+ installers.set(name, install)
32
+ return install
33
+ } catch {
34
+ return undefined
35
+ }
36
+ }
37
+
17
38
  type Recorded = { event: AnyEventClass; payload: unknown }
18
39
 
19
40
  /** Records emitted events instead of running listeners. */
@@ -59,5 +80,9 @@ registerFake('events', (app) => {
59
80
  declare module './fakes' {
60
81
  interface TestFakes {
61
82
  events: EventFake
83
+ queue: import('@cslug/queue').QueueFake
84
+ mail: import('@cslug/mail').MailFake
85
+ storage: import('@cslug/storage').StorageFake
86
+ notify: import('@cslug/notification').NotificationFake
62
87
  }
63
88
  }
package/src/request.ts CHANGED
@@ -6,6 +6,13 @@ type Assertion = (res: TestResponse) => void | Promise<void>
6
6
  export type Handler = (request: Request) => Promise<Response>
7
7
 
8
8
  /** The session of the test's cookie jar (created if needed), to read and write as a request would. */
9
+ /** The session data of the jar's session cookie, or undefined (never creates a session). */
10
+ export async function readSession(app: Application, jar: CookieJar): Promise<Record<string, unknown> | undefined> {
11
+ const id = jar.cookies.get(app.config<string | undefined>('session.cookie') ?? 'cslug_session')
12
+ return id ? ((await app.resolve(SessionStore).read(id)) ?? undefined) : undefined
13
+ }
14
+
15
+ /** The session behind a test client's cookie jar (created when missing), to read and seed it. */
9
16
  export async function testSession(app: Application, jar: CookieJar) {
10
17
  const name = app.config<string | undefined>('session.cookie') ?? 'cslug_session'
11
18
  const store = app.resolve(SessionStore)
@@ -58,8 +65,22 @@ export class TestResponse {
58
65
  readonly response: Response,
59
66
  readonly request: Request,
60
67
  private readonly ctx: { app: Application; jar: CookieJar },
68
+ /** Pages rendered by `view()` for this request (needs @cslug/vue). */
69
+ readonly views: { page: unknown; props: Record<string, unknown> }[] = [],
61
70
  ) {}
62
71
 
72
+ /** The islands in the HTML: `{ id: 'components/todo-item', props }` (`data-island`, `data-props`). */
73
+ async islands(): Promise<{ id: string; props: Record<string, unknown> }[]> {
74
+ const html = await this.body()
75
+ return [...html.matchAll(/<cslug-island\b([^>]*)>/g)].map(([, attrs]) => {
76
+ const attr = (name: string) => new RegExp(`${name}="([^"]*)"`).exec(attrs ?? '')?.[1] ?? ''
77
+ const decoded = attr('data-props').replace(/&(quot|amp|lt|gt|#39);/g, (_m, e: string) =>
78
+ e === 'quot' ? '"' : e === 'amp' ? '&' : e === 'lt' ? '<' : e === 'gt' ? '>' : "'",
79
+ )
80
+ return { id: attr('data-island'), props: decoded ? (JSON.parse(decoded) as Record<string, unknown>) : {} }
81
+ })
82
+ }
83
+
63
84
  get status(): number {
64
85
  return this.response.status
65
86
  }
@@ -111,6 +132,8 @@ export class PendingRequest implements PromiseLike<TestResponse> {
111
132
  handle: Handler
112
133
  host: string
113
134
  before: ((r: PendingRequest) => void | Promise<void>)[]
135
+ /** After each request (the test kit refreshes `t.auth` here). */
136
+ after?: (() => Promise<void>)[]
114
137
  },
115
138
  ) {}
116
139
 
@@ -136,6 +159,7 @@ export class PendingRequest implements PromiseLike<TestResponse> {
136
159
  }
137
160
  /** A JSON body (also sets Accept: application/json). */
138
161
  json(data: unknown): this {
162
+ this.jsonCsrf = true
139
163
  this.hdrs.set('content-type', 'application/json')
140
164
  if (!this.hdrs.has('accept')) this.hdrs.set('accept', 'application/json')
141
165
  this.body = JSON.stringify(data, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))
@@ -161,6 +185,8 @@ export class PendingRequest implements PromiseLike<TestResponse> {
161
185
  return this
162
186
  }
163
187
  private formCsrf = false
188
+ /** JSON writes carry the session's CSRF token in `X-CSRF-Token`, as an island's `useForm` does. */
189
+ private jsonCsrf = false
164
190
 
165
191
  // ── assertions (queued; run when awaited) ───────────────────────────────────────────────────────────
166
192
  private assert(fn: Assertion): this {
@@ -241,6 +267,34 @@ export class PendingRequest implements PromiseLike<TestResponse> {
241
267
  assertSessionMissing(key: string) {
242
268
  return this.assert(async (r) => expect(await r.session()).not.toHaveProperty([key]))
243
269
  }
270
+ /** The page was rendered with `view(View, props)`; `fn` gets the props (use `expect` in it). */
271
+ assertView(view: unknown, fn?: (props: Record<string, unknown>) => unknown) {
272
+ return this.assert(async (r) => {
273
+ const found = r.views.find((v) => v.page === view)
274
+ const name = (v: unknown) =>
275
+ (v as { __name?: string; name?: string })?.__name ?? (v as { name?: string })?.name ?? 'a view'
276
+ expect(
277
+ found,
278
+ `expected ${name(view)} to be rendered; rendered: ${r.views.map((v) => name(v.page)).join(', ') || 'no view'}`,
279
+ ).toBeDefined()
280
+ await fn?.((found as { props: Record<string, unknown> }).props)
281
+ })
282
+ }
283
+ /** An island `name` (`'todo-item'` or `'components/todo-item'`) is in the page, with at least these props (deep). */
284
+ assertIsland(name: string, props?: Record<string, unknown>) {
285
+ return this.assert(async (r) => {
286
+ const islands = (await r.islands()).filter((i) => i.id === name || i.id.endsWith(`/${name}`))
287
+ expect(
288
+ islands.length,
289
+ `no island ${name}; islands: ${(await r.islands()).map((i) => i.id).join(', ') || 'none'}`,
290
+ ).toBeGreaterThan(0)
291
+ if (props)
292
+ expect(
293
+ islands.some((i) => matches(i.props, props)),
294
+ `no ${name} island with props ${JSON.stringify(props)}`,
295
+ ).toBe(true)
296
+ })
297
+ }
244
298
  assertSee(text: string) {
245
299
  return this.assert(async (r) => expect(await r.body()).toContain(text))
246
300
  }
@@ -285,14 +339,28 @@ export class PendingRequest implements PromiseLike<TestResponse> {
285
339
  const cookie = this.ctx.jar.header()
286
340
  if (cookie && !this.hdrs.has('cookie')) this.hdrs.set('cookie', cookie)
287
341
  if (this.formCsrf) await this.addCsrf(url)
342
+ if (this.jsonCsrf && !['GET', 'HEAD'].includes(this.method) && !this.hdrs.has('x-csrf-token'))
343
+ this.hdrs.set('x-csrf-token', await this.csrfToken())
344
+ const marker = Bun.randomUUIDv7()
345
+ this.hdrs.set(TEST_REQUEST_HEADER, marker)
288
346
  const request = new Request(url, {
289
347
  method: this.method,
290
348
  headers: this.hdrs,
291
349
  body: this.method === 'GET' || this.method === 'HEAD' ? undefined : this.body,
292
350
  })
293
- const response = await this.ctx.handle(request)
351
+ const views: TestResponse['views'] = []
352
+ const stop = (await vueHooks())?.onView((page, props, ctx) => {
353
+ if (ctx.request.header(TEST_REQUEST_HEADER) === marker) views.push({ page, props })
354
+ })
355
+ let response: Response
356
+ try {
357
+ response = await this.ctx.handle(request)
358
+ } finally {
359
+ stop?.()
360
+ }
294
361
  this.ctx.jar.store(response)
295
- const res = new TestResponse(response, request, this.ctx)
362
+ for (const hook of this.ctx.after ?? []) await hook()
363
+ const res = new TestResponse(response, request, this.ctx, views)
296
364
  for (const a of this.assertions) await a(res)
297
365
  return res
298
366
  }
@@ -302,6 +370,11 @@ export class PendingRequest implements PromiseLike<TestResponse> {
302
370
  if (!this.hdrs.has('referer')) this.hdrs.set('referer', url.toString())
303
371
  const params = this.body as URLSearchParams
304
372
  if (params.has('_token')) return
373
+ params.set('_token', await this.csrfToken())
374
+ }
375
+
376
+ /** The session's CSRF token (the session and the token are created if needed). */
377
+ private async csrfToken(): Promise<string> {
305
378
  const session = await testSession(this.ctx.app, this.ctx.jar)
306
379
  this.hdrs.set('cookie', this.ctx.jar.header() ?? '')
307
380
  let token = session.data._token as string | undefined
@@ -309,7 +382,7 @@ export class PendingRequest implements PromiseLike<TestResponse> {
309
382
  token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
310
383
  await session.write({ _token: token })
311
384
  }
312
- params.set('_token', token)
385
+ return token
313
386
  }
314
387
 
315
388
  // biome-ignore lint/suspicious/noThenProperty: a PendingRequest is awaited to run it
@@ -321,3 +394,29 @@ export class PendingRequest implements PromiseLike<TestResponse> {
321
394
  return this.result.then(onFulfilled, onRejected)
322
395
  }
323
396
  }
397
+
398
+ /** Marks test requests so `assertView` sees only its own request's views. */
399
+ const TEST_REQUEST_HEADER = 'x-cslug-test-request'
400
+
401
+ type VueHooks = {
402
+ onView(
403
+ fn: (
404
+ page: unknown,
405
+ props: Record<string, unknown>,
406
+ ctx: { request: { header(n: string): string | undefined } },
407
+ ) => void,
408
+ ): () => void
409
+ }
410
+ let vue: Promise<VueHooks | undefined> | undefined
411
+ /** @cslug/vue's view hook, if installed. */
412
+ const vueHooks = () => {
413
+ vue ??= import('@cslug/vue').then((m) => m as unknown as VueHooks).catch(() => undefined)
414
+ return vue
415
+ }
416
+
417
+ /** Deep subset match (arrays: every expected item matches some actual item at the same index). */
418
+ function matches(actual: unknown, expected: unknown): boolean {
419
+ if (expected === null || typeof expected !== 'object') return Object.is(actual, expected)
420
+ if (actual === null || typeof actual !== 'object') return false
421
+ return Object.entries(expected).every(([k, v]) => matches((actual as Record<string, unknown>)[k], v))
422
+ }
package/src/test-app.ts CHANGED
@@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect } from 'bun:test'
2
2
  import { join } from 'node:path'
3
3
  import {
4
4
  type Application,
5
+ type AuthUser,
5
6
  Cache,
6
7
  Clock,
7
8
  FakeClock,
@@ -15,8 +16,8 @@ import {
15
16
  SessionStore,
16
17
  type Token,
17
18
  } from '@cslug/core'
18
- import { fakeInstaller, type TestFakes } from './fakes'
19
- import { CookieJar, type Handler, PendingRequest, testSession } from './request'
19
+ import { loadFake, type TestFakes } from './fakes'
20
+ import { CookieJar, type Handler, PendingRequest, readSession, testSession } from './request'
20
21
 
21
22
  type Db = {
22
23
  value(q: unknown): Promise<unknown>
@@ -33,7 +34,7 @@ export type TestAppOptions = {
33
34
  /** Config overrides, by dotted path: `{ 'payments.driver': 'fake' }`. */
34
35
  config?: Record<string, unknown>
35
36
  /** Fakes to install for every test: `'events'`, and those packages add (`'queue'`, `'mail'`, …). */
36
- fakes?: (keyof TestFakes | string)[]
37
+ fakes?: readonly (keyof TestFakes | (string & {}))[]
37
38
  /**
38
39
  * Database isolation per test. `'transaction'` (default): every test runs in a transaction that is rolled
39
40
  * back. `'truncate'`: real commits, tables truncated after each test (for concurrency, locks, after-commit
@@ -62,11 +63,24 @@ export type TestApp = {
62
63
  beforeRequest(hook: (r: PendingRequest) => void | Promise<void>): void
63
64
  /** Requests of this test run as `user` (signed in through the session, like `auth.login`). Needs @cslug/auth. */
64
65
  actingAs(user: { id: unknown }): void
66
+ /** Who is signed in after the last request (through the session). Needs @cslug/auth. */
67
+ readonly auth: { check(): boolean; user(): AuthUser | null }
68
+ /** API tokens (@cslug/auth): `const { plainText } = await t.tokens.create(user, { abilities: ['todos:read'] })`. */
69
+ readonly tokens: {
70
+ create(
71
+ user: { id: unknown },
72
+ options?: { abilities?: string[]; name?: string; expiresIn?: string | number },
73
+ ): Promise<{ plainText: string }>
74
+ }
65
75
  readonly db: {
66
76
  /** `count('ledger_entries', { bookingId })`: camelCase keys, snake_case columns. */
67
77
  count(table: string, where?: Record<string, unknown>): Promise<number>
68
78
  find(table: string, id: unknown): Promise<Record<string, unknown> | null>
69
79
  }
80
+ /** The scheduler (needs @cslug/queue's ScheduleProvider): `runDue()` runs what is due at the fake clock's time. */
81
+ readonly schedule: {
82
+ runDue(): Promise<import('@cslug/queue').ScheduleRun[]>
83
+ }
70
84
  assertDatabaseHas(table: string, where: Record<string, unknown>): Promise<void>
71
85
  assertDatabaseMissing(table: string, where: Record<string, unknown>): Promise<void>
72
86
  } & Partial<TestFakes>
@@ -80,7 +94,9 @@ export type TestApp = {
80
94
  * test('…', async () => { await t.get('/todos').assertOk() })
81
95
  * ```
82
96
  */
83
- export function testApp(options: TestAppOptions = {}): TestApp {
97
+ export function testApp<const F extends readonly string[] = []>(
98
+ options: TestAppOptions & { fakes?: F } = {},
99
+ ): TestApp & Pick<TestFakes, Extract<F[number], keyof TestFakes>> {
84
100
  let app: Application | undefined
85
101
  let db: Db | undefined
86
102
  let dbModule: DatabaseModule | undefined
@@ -88,6 +104,20 @@ export function testApp(options: TestAppOptions = {}): TestApp {
88
104
  let clock = new FakeClock()
89
105
  const jar = new CookieJar()
90
106
  const hooks: ((r: PendingRequest) => void | Promise<void>)[] = []
107
+ let signedIn: AuthUser | null = null
108
+ /** After each request: who the session says is signed in. */
109
+ const after = [
110
+ async () => {
111
+ const a = need()
112
+ const id = (await readSession(a, jar))?.['auth.id']
113
+ if (id === undefined || id === null) {
114
+ signedIn = null
115
+ return
116
+ }
117
+ const { userSource } = await authModule()
118
+ signedIn = ((await (await userSource(a)).find(id)) as AuthUser | null) ?? null
119
+ },
120
+ ]
91
121
  const fakes: Record<string, unknown> = {}
92
122
  let handle: Handler | undefined
93
123
 
@@ -128,13 +158,14 @@ export function testApp(options: TestAppOptions = {}): TestApp {
128
158
  const a = need()
129
159
  jar.clear()
130
160
  hooks.length = 0
161
+ signedIn = null
131
162
  clock = new FakeClock(a.config<string | undefined>('app.timezone') ?? 'UTC')
132
163
  a.swap(Clock, clock)
133
164
  // in-memory stores start empty in every test (rate limits, locks, cache, sessions); Redis ones are left alone
134
165
  for (const [contract, Memory] of MEMORY_DRIVERS)
135
166
  if (a.resolve(contract as Token<unknown>) instanceof Memory) a.swap(contract as Token<unknown>, new Memory())
136
167
  for (const name of options.fakes ?? []) {
137
- const install = fakeInstaller(String(name))
168
+ const install = await loadFake(String(name))
138
169
  if (!install) throw new Error(`testApp(): no fake named "${String(name)}" (is its package installed?)`)
139
170
  fakes[String(name)] = install(a)
140
171
  }
@@ -162,13 +193,16 @@ export function testApp(options: TestAppOptions = {}): TestApp {
162
193
  const a = need()
163
194
  if (!handle) throw new Error('testApp(): HTTP requests need @cslug/http and HttpProvider')
164
195
  const host = options.host ?? hostOf(a.config<string | undefined>('app.url'))
165
- return new PendingRequest(method, path, { app: a, jar, handle, host, before: hooks })
196
+ return new PendingRequest(method, path, { app: a, jar, handle, host, before: hooks, after })
166
197
  }
167
198
 
168
199
  const whereSql = (sqlTag: DatabaseModule['sql'], where: Record<string, unknown>) => {
169
200
  const parts = Object.entries(where).map(([k, v]) => {
170
201
  const column = sqlTag.ident(k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`))
171
- return v === null ? sqlTag`${column} is null` : sqlTag`${column} = ${v}`
202
+ if (v === null) return sqlTag`${column} is null`
203
+ // operators from @cslug/database: { remindedAt: notNull() }, { dueOn: lte('2027-03-01') }
204
+ if (dbModule && v instanceof dbModule.Op) return v.render(column)
205
+ return sqlTag`${column} = ${v}`
172
206
  })
173
207
  return parts.length ? sqlTag` where ${sqlTag.join(parts, sqlTag` and `)}` : sqlTag``
174
208
  }
@@ -203,6 +237,35 @@ export function testApp(options: TestAppOptions = {}): TestApp {
203
237
  beforeRequest: (hook: (r: PendingRequest) => void | Promise<void>) => {
204
238
  hooks.push(hook)
205
239
  },
240
+ auth: {
241
+ check: () => signedIn !== null,
242
+ user: () => signedIn,
243
+ },
244
+ tokens: {
245
+ async create(
246
+ user: { id: unknown },
247
+ options: { abilities?: string[]; name?: string; expiresIn?: string | number } = {},
248
+ ) {
249
+ const { Tokens } = await authModule()
250
+ const { plainText } = await need()
251
+ .resolve(Tokens)
252
+ .create(user, {
253
+ name: options.name ?? 'test',
254
+ abilities: options.abilities,
255
+ expiresIn: options.expiresIn,
256
+ })
257
+ return { plainText }
258
+ },
259
+ },
260
+ schedule: {
261
+ async runDue() {
262
+ const a = need()
263
+ const { Scheduler } = await import('@cslug/queue')
264
+ if (!a.has(Scheduler)) throw new Error('testApp(): t.schedule needs ScheduleProvider (@cslug/queue)')
265
+ // no once-per-tick lock: tests replay the same tick
266
+ return a.resolve(Scheduler).runDue(clock.now(), { exclusive: false })
267
+ },
268
+ },
206
269
  db: {
207
270
  async count(table: string, where: Record<string, unknown> = {}) {
208
271
  const { db, sql } = dbOrFail()
@@ -228,7 +291,7 @@ export function testApp(options: TestAppOptions = {}): TestApp {
228
291
  if (typeof key === 'string' && key in fakes) return fakes[key]
229
292
  return Reflect.get(target, key, receiver)
230
293
  },
231
- }) as unknown as TestApp
294
+ }) as unknown as TestApp & Pick<TestFakes, Extract<F[number], keyof TestFakes>>
232
295
  }
233
296
 
234
297
  const MEMORY_DRIVERS = [
@@ -254,3 +317,25 @@ async function defaultApp(): Promise<Application> {
254
317
  throw new Error(`testApp(): ${path} must export createApp(), or pass testApp({ create })`)
255
318
  return mod.createApp()
256
319
  }
320
+
321
+ /**
322
+ * @cslug/auth, loaded at runtime with a local type: importing its types here would load a second copy of its
323
+ * `HttpContext` augmentation when the workspace is reachable through two paths.
324
+ */
325
+ type AuthModule = {
326
+ userSource(app: Application): Promise<{ find(id: unknown): Promise<object | null> }>
327
+ Tokens: Token<{
328
+ create(
329
+ user: unknown,
330
+ options: { name: string; abilities?: string[]; expiresIn?: string | number },
331
+ ): Promise<{ plainText: string }>
332
+ }>
333
+ }
334
+ const AUTH_PACKAGE: string = '@cslug/auth'
335
+ const authModule = async (): Promise<AuthModule> => {
336
+ try {
337
+ return (await import(AUTH_PACKAGE)) as AuthModule
338
+ } catch {
339
+ throw new Error('testApp(): t.auth and t.tokens need @cslug/auth')
340
+ }
341
+ }