Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

native-runtime-vitest.test.ts

437 lines14.2 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import * as capacitor from '../e2e/app/src/runtime-vitest'
3import * as tauri from '../../tauri-db-sqlite-persistence/e2e/app/src/runtime-vitest'
4import {
5 getPersistedConformanceTestNames,
6 persistedConformanceLaws,
7} from '../../db-collection-e2e/src/fixtures/persisted-conformance-manifest'
8​
9const runtimes = [
10 ['capacitor', capacitor],
11 ['tauri', tauri],
12] as const
13​
14beforeEach(() => {
15 for (const [, runtime] of runtimes) runtime.resetRegisteredTests()
16})
17​
18afterEach(() => {
19 vi.doUnmock('vitest')
20 vi.resetModules()
21 for (const [, runtime] of runtimes) runtime.resetRegisteredTests()
22})
23​
24describe.each(runtimes)('%s native test runner', (_name, runtime) => {
25 it('records each literal law once without counting hooks as laws', async () => {
26 const calls: Array<string> = []
27 runtime.describe('suite', () => {
28 runtime.beforeAll(() => {
29 calls.push('setup')
30 })
31 runtime.it('first', () => {
32 calls.push('first')
33 })
34 runtime.it('second', () => {
35 calls.push('second')
36 })
37 runtime.afterAll(() => {
38 calls.push('cleanup')
39 })
40 })
41 const result = await runtime.runRegisteredTests({
42 expectedTestNames: ['suite > first', 'suite > second'],
43 })
44 expect(result.complete).toBe(true)
45 expect(result.failed).toBe(0)
46 expect([
47 result.expected,
48 result.registered,
49 result.executed,
50 result.total,
51 result.passed,
52 ]).toStrictEqual([2, 2, 2, 2, 2])
53 expect(result.executedNames).toStrictEqual([
54 'suite > first',
55 'suite > second',
56 ])
57 expect(result.results.map((entry) => entry.kind)).toStrictEqual([
58 'test',
59 'test',
60 ])
61 expect(calls).toStrictEqual(['setup', 'first', 'second', 'cleanup'])
62 })
63​
64 it('rejects an empty registry and an empty expected manifest', async () => {
65 const missing = await runtime.runRegisteredTests({
66 expectedTestNames: ['suite > first'],
67 })
68 expect(missing.complete).toBe(false)
69 expect(missing.missingNames).toStrictEqual(['suite > first'])
70 expect([
71 missing.registered,
72 missing.executed,
73 missing.failed,
74 ]).toStrictEqual([0, 0, 0])
75 const empty = await runtime.runRegisteredTests({ expectedTestNames: [] })
76 expect(empty.complete).toBe(false)
77 expect(empty.manifestErrors).toContain('Expected law manifest is empty')
78 })
79​
80 it('rejects an equal-count wrong name and a duplicate replacing a required law', async () => {
81 runtime.describe('suite', () => {
82 runtime.it('first', () => {})
83 runtime.it('wrong', () => {})
84 })
85 const wrong = await runtime.runRegisteredTests({
86 expectedTestNames: ['suite > first', 'suite > second'],
87 })
88 expect(wrong.complete).toBe(false)
89 expect([wrong.registered, wrong.executed]).toStrictEqual([2, 2])
90 expect(wrong.missingNames).toStrictEqual(['suite > second'])
91 expect(wrong.unexpectedNames).toStrictEqual(['suite > wrong'])
92 runtime.resetRegisteredTests()
93 runtime.describe('suite', () => {
94 runtime.it('first', () => {})
95 runtime.it('first', () => {})
96 })
97 const duplicate = await runtime.runRegisteredTests({
98 expectedTestNames: ['suite > first', 'suite > second'],
99 })
100 expect(duplicate.complete).toBe(false)
101 expect(duplicate.registeredNames).toStrictEqual([
102 'suite > first',
103 'suite > first',
104 ])
105 expect(duplicate.duplicateNames).toStrictEqual(['suite > first'])
106 expect(duplicate.missingNames).toStrictEqual(['suite > second'])
107 })
108​
109 it('retains skipped and nested-skipped declarations without running hooks or bodies', async () => {
110 const body = vi.fn()
111 runtime.describe.skip('suite', () => {
112 runtime.beforeAll(body)
113 runtime.afterAll(body)
114 runtime.it('first', body)
115 runtime.describe('nested', () => {
116 runtime.beforeEach(body)
117 runtime.afterEach(body)
118 runtime.it('second', body)
119 runtime.it.skip('third', body)
120 })
121 })
122 const result = await runtime.runRegisteredTests({
123 expectedTestNames: [
124 'suite > first',
125 'suite > nested > second',
126 'suite > nested > third',
127 ],
128 })
129 expect(result.complete).toBe(false)
130 expect([result.registered, result.executed, result.skipped]).toStrictEqual([
131 3, 0, 3,
132 ])
133 expect(result.skippedNames).toStrictEqual([
134 'suite > first',
135 'suite > nested > second',
136 'suite > nested > third',
137 ])
138 expect(body).not.toHaveBeenCalled()
139 })
140​
141 it('reports failed setup laws as unexecuted and attempts every teardown hook', async () => {
142 const bodies = vi.fn()
143 const cleanups: Array<number> = []
144 runtime.describe('suite', () => {
145 runtime.beforeAll(() => {
146 throw undefined
147 })
148 runtime.it('first', bodies)
149 runtime.describe('nested', () => {
150 runtime.it('second', bodies)
151 })
152 runtime.afterAll(() => {
153 cleanups.push(1)
154 throw new Error('cleanup-one')
155 })
156 runtime.afterAll(() => {
157 cleanups.push(2)
158 throw new Error('cleanup-two')
159 })
160 })
161 const result = await runtime.runRegisteredTests({
162 expectedTestNames: ['suite > first', 'suite > nested > second'],
163 })
164 expect(result.complete).toBe(false)
165 expect([
166 result.registered,
167 result.executed,
168 result.unexecuted,
169 result.total,
170 result.failed,
171 ]).toStrictEqual([2, 0, 2, 2, 3])
172 expect(result.unexecutedNames).toStrictEqual([
173 'suite > first',
174 'suite > nested > second',
175 ])
176 expect(
177 result.results
178 .filter((entry) => entry.kind === 'hook')
179 .map((entry) => entry.error),
180 ).toStrictEqual(['undefined', 'cleanup-one', 'cleanup-two'])
181 expect(cleanups).toStrictEqual([1, 2])
182 expect(bodies).not.toHaveBeenCalled()
183 })
184​
185 it('separates beforeEach failure from actual body execution and preserves cleanup errors', async () => {
186 let entered = 0
187 const bodies: Array<string> = []
188 runtime.describe('suite', () => {
189 runtime.beforeEach(() => {
190 if (entered++ === 0) throw new Error('first setup')
191 })
192 runtime.afterEach(() => {
193 throw new Error('after each')
194 })
195 runtime.it('first', () => {
196 bodies.push('first')
197 })
198 runtime.it('second', () => {
199 bodies.push('second')
200 })
201 })
202 const result = await runtime.runRegisteredTests({
203 expectedTestNames: ['suite > first', 'suite > second'],
204 })
205 expect(result.complete).toBe(false)
206 expect(result.executedNames).toStrictEqual(['suite > second'])
207 expect(result.unexecutedNames).toStrictEqual(['suite > first'])
208 expect(result.failed).toBe(3)
209 expect(bodies).toStrictEqual(['second'])
210 })
211​
212 it('keeps body and cleanup failures even when all required bodies executed', async () => {
213 runtime.it('law', () => {
214 throw new Error('body')
215 })
216 runtime.afterAll(() => {
217 throw new Error('cleanup')
218 })
219 const result = await runtime.runRegisteredTests({
220 expectedTestNames: ['law'],
221 })
222 expect(result.complete).toBe(true)
223 expect(result.failed).toBe(2)
224 expect(result.complete && result.failed === 0).toBe(false)
225 expect(
226 result.results.map((entry) => [entry.kind, entry.error]),
227 ).toStrictEqual([
228 ['test', 'body'],
229 ['hook', 'cleanup'],
230 ])
231 })
232​
233 it('rejects duplicate authority and registration changes during execution', async () => {
234 runtime.it('law', () => {
235 runtime.it('late', () => {})
236 })
237 const changed = await runtime.runRegisteredTests({
238 expectedTestNames: ['law'],
239 })
240 expect(changed.complete).toBe(false)
241 expect(changed.manifestErrors).toContain(
242 'Law registration changed during execution',
243 )
244 runtime.resetRegisteredTests()
245 runtime.it('law', () => {})
246 const duplicate = await runtime.runRegisteredTests({
247 expectedTestNames: ['law', 'law'],
248 })
249 expect(duplicate.complete).toBe(false)
250 expect(duplicate.manifestErrors).toContain(
251 'Expected law manifest has duplicate names',
252 )
253 })
254​
255 it('preserves the required ordinary matcher calls', () => {
256 runtime.expect(2).toBe(2)
257 runtime.expect([1, 2]).toEqual([1, 2])
258 runtime.expect(2).toBeGreaterThan(1)
259 runtime.expect(2).toBeGreaterThanOrEqual(2)
260 runtime.expect(2).toBeLessThan(3)
261 runtime.expect(2).toBeLessThanOrEqual(2)
262 runtime.expect(true).toBeTruthy()
263 runtime.expect(false).toBeDefined()
264 runtime.expect(null).toBeNull()
265 runtime.expect(['x']).toContain('x')
266 runtime.expect({ field: undefined }).toHaveProperty('field')
267 runtime.expect([1, 2]).toHaveLength(2)
268 runtime.expect([1]).not.toEqual([2])
269 })
270​
271 it('strictly preserves native Date, BigInt, nullable and nested own-key values', () => {
272 const expected = {
273 date: new Date(1700000000123),
274 count: 9007199254740993n,
275 nullable: null,
276 metadata: { tags: ['a', undefined] },
277 }
278 runtime.expect(structuredClone(expected)).toStrictEqual(expected)
279 runtime
280 .expect(structuredClone(expected))
281 .not.toStrictEqual({ ...expected, count: 1n })
282 const ownUndefined = structuredClone(expected)
283 Object.defineProperty(ownUndefined.metadata, 'extra', {
284 value: undefined,
285 enumerable: true,
286 })
287 const faults: Array<unknown> = [
288 ownUndefined,
289 { ...expected, date: expected.date.toISOString() },
290 { ...expected, date: new Date(1700000000124) },
291 { ...expected, date: {} },
292 { ...expected, count: Number(expected.count) },
293 {
294 date: expected.date,
295 count: expected.count,
296 metadata: expected.metadata,
297 },
298 ]
299 for (const fault of faults)
300 expect(() => runtime.expect(fault).toStrictEqual(expected)).toThrow()
301 const sparse = new Array(1)
302 expect(() => runtime.expect(sparse).toStrictEqual([undefined])).toThrow()
303 expect(() => runtime.expect([undefined]).toStrictEqual(sparse)).toThrow()
304 class Box {
305 value = 1
306 }
307 expect(() =>
308 runtime.expect(new Box()).toStrictEqual({ value: 1 }),
309 ).toThrow()
310 expect(() => runtime.expect(new Map()).toStrictEqual(new Map())).toThrow(
311 'Unsupported object kind',
312 )
313 runtime.expect(structuredClone(expected)).toStrictEqual(expected)
314 })
315​
316 it('supports synchronous no-argument throws including undefined without accepting a no-throw', () => {
317 runtime
318 .expect(() => {
319 throw undefined
320 })
321 .toThrow()
322 runtime
323 .expect(() => {
324 throw new Error('sentinel')
325 })
326 .toThrow()
327 runtime.expect(() => {}).not.toThrow()
328 expect(() => runtime.expect(() => {}).toThrow()).toThrow()
329 expect(() =>
330 runtime
331 .expect(() => {
332 throw undefined
333 })
334 .not.toThrow(),
335 ).toThrow()
336 expect(() => runtime.expect(1).toThrow()).toThrow('synchronous function')
337 expect(() => runtime.expect(() => Promise.resolve(1)).toThrow()).toThrow(
338 'async functions',
339 )
340 })
341​
342 it('waitFor returns nonthrowing false, undefined and values and retries thrown assertions', async () => {
343 expect(await runtime.vi.waitFor(() => false)).toBe(false)
344 expect(await runtime.vi.waitFor(() => undefined)).toBeUndefined()
345 const value = { complete: true }
346 expect(await runtime.vi.waitFor(() => value)).toBe(value)
347 let attempts = 0
348 const result = await runtime.vi.waitFor(
349 () => {
350 if (++attempts < 3) throw new Error('not yet')
351 return value
352 },
353 { interval: 1, timeout: 1000 },
354 )
355 expect(result).toBe(value)
356 expect(attempts).toBe(3)
357 })
358​
359 it('waitFor preserves the final thrown value at timeout and rejects unsupported inputs', async () => {
360 const error = new Error('last assertion')
361 await expect(
362 runtime.vi.waitFor(
363 () => {
364 throw error
365 },
366 { interval: 1, timeout: 5 },
367 ),
368 ).rejects.toBe(error)
369 const undefinedOutcome = await runtime.vi
370 .waitFor(
371 () => {
372 throw undefined
373 },
374 { timeout: 0 },
375 )
376 .then(
377 () => ({ status: 'fulfilled' }),
378 (failure) => ({ status: 'rejected', failure }),
379 )
380 expect(undefinedOutcome).toStrictEqual({
381 status: 'rejected',
382 failure: undefined,
383 })
384 await expect(runtime.vi.waitFor(() => Promise.resolve(1))).rejects.toThrow(
385 'synchronous assertion',
386 )
387 await expect(runtime.vi.waitFor(() => 1, { interval: 0 })).rejects.toThrow(
388 'Invalid',
389 )
390 await expect(
391 runtime.vi.waitFor(() => 1, { timeout: Number.NaN }),
392 ).rejects.toThrow('Invalid')
393 })
394​
395 it('waitFor observes rejected async results while retaining its synchronous-only boundary', async () => {
396 for (const failure of [new Error('unsupported async failure'), undefined]) {
397 const result = Promise.reject(failure)
398 await expect(runtime.vi.waitFor(() => result)).rejects.toThrow(
399 'synchronous assertion',
400 )
401 // Let the host report any unhandled rejection from the actual result.
402 await new Promise<void>((resolve) => setTimeout(resolve, 0))
403 }
404 expect(await runtime.vi.waitFor(() => 'healthy neighbor')).toBe(
405 'healthy neighbor',
406 )
407 })
408​
409 // Cold-loading all shared suites can exceed the default budget under CI
410 // instrumentation. This checks registration, not database response time.
411 it(
412 'registers the actual shared113 declarations against an independent literal manifest without database hooks',
413 { timeout: 30_000 },
414 async () => {
415 vi.resetModules()
416 vi.doMock('vitest', () => runtime)
417 const { runPersistedCollectionConformanceSuite } =
418 await import('../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract')
419 const getConfig = vi.fn(() => {
420 throw new Error(
421 'Database access is forbidden in registration-only control',
422 )
423 })
424 runPersistedCollectionConformanceSuite(
425 'isolated persisted conformance',
426 getConfig,
427 )
428 expect(persistedConformanceLaws).toHaveLength(113)
429 expect(new Set(persistedConformanceLaws).size).toBe(113)
430 expect(runtime.getRegisteredTestCount()).toBe(113)
431 expect(runtime.getRegisteredTestNames()).toStrictEqual(
432 getPersistedConformanceTestNames('isolated persisted conformance'),
433 )
434 expect(getConfig).not.toHaveBeenCalled()
435 },
436 )
437})