@omnitron-dev/testing 0.4.4 → 0.4.6

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 (122) hide show
  1. package/README.md +43 -0
  2. package/dist/async/events.js.map +1 -1
  3. package/dist/async/index.d.ts +5 -5
  4. package/dist/async/index.js +5 -5
  5. package/dist/async/index.js.map +1 -1
  6. package/dist/async/retry.js.map +1 -1
  7. package/dist/async/wait.js.map +1 -1
  8. package/dist/docker/database-manager.js +13 -15
  9. package/dist/docker/database-manager.js.map +1 -1
  10. package/dist/docker/docker-test-manager.d.ts +12 -3
  11. package/dist/docker/docker-test-manager.js +286 -255
  12. package/dist/docker/docker-test-manager.js.map +1 -1
  13. package/dist/docker/redis-manager.js +70 -95
  14. package/dist/docker/redis-manager.js.map +1 -1
  15. package/dist/docker/types.d.ts +7 -2
  16. package/dist/env.d.ts +11 -0
  17. package/dist/env.js +21 -0
  18. package/dist/env.js.map +1 -0
  19. package/dist/errors.js.map +1 -1
  20. package/dist/helpers/assertions.js +3 -3
  21. package/dist/helpers/assertions.js.map +1 -1
  22. package/dist/index.d.ts +1 -1
  23. package/dist/runtime/bun-adapter.d.ts +23 -1
  24. package/dist/runtime/bun-adapter.js +14 -1
  25. package/dist/runtime/bun-adapter.js.map +1 -1
  26. package/dist/runtime/deno-adapter.d.ts +72 -15
  27. package/dist/runtime/deno-adapter.js +93 -78
  28. package/dist/runtime/deno-adapter.js.map +1 -1
  29. package/dist/runtime/node-adapter.d.ts +15 -3
  30. package/dist/runtime/node-adapter.js +1 -1
  31. package/dist/runtime/node-adapter.js.map +1 -1
  32. package/dist/runtime/test-adapter.d.ts +1 -1
  33. package/dist/runtime/test-adapter.js +12 -14
  34. package/dist/runtime/test-adapter.js.map +1 -1
  35. package/dist/titan/database/database-testing.module.d.ts +7 -6
  36. package/dist/titan/database/database-testing.module.js +40 -26
  37. package/dist/titan/database/database-testing.module.js.map +1 -1
  38. package/dist/titan/database/index.d.ts +1 -1
  39. package/dist/titan/database/index.js +1 -1
  40. package/dist/titan/database/index.js.map +1 -1
  41. package/dist/titan/database/test-utilities.d.ts +2 -2
  42. package/dist/titan/database/test-utilities.js +3 -2
  43. package/dist/titan/database/test-utilities.js.map +1 -1
  44. package/dist/titan/index.d.ts +9 -9
  45. package/dist/titan/index.js +6 -6
  46. package/dist/titan/index.js.map +1 -1
  47. package/dist/titan/nexus/mock-provider.js +6 -6
  48. package/dist/titan/nexus/mock-provider.js.map +1 -1
  49. package/dist/titan/nexus/test-container.js +10 -10
  50. package/dist/titan/nexus/test-container.js.map +1 -1
  51. package/dist/titan/nexus/test-utilities.js +9 -9
  52. package/dist/titan/nexus/test-utilities.js.map +1 -1
  53. package/dist/titan/pm/mock-process-spawner.d.ts +4 -3
  54. package/dist/titan/pm/mock-process-spawner.js +37 -15
  55. package/dist/titan/pm/mock-process-spawner.js.map +1 -1
  56. package/dist/titan/pm/mock-spawner.d.ts +2 -1
  57. package/dist/titan/pm/mock-spawner.js +3 -1
  58. package/dist/titan/pm/mock-spawner.js.map +1 -1
  59. package/dist/titan/pm/test-process-manager.d.ts +4 -4
  60. package/dist/titan/pm/test-process-manager.js +7 -3
  61. package/dist/titan/pm/test-process-manager.js.map +1 -1
  62. package/dist/titan/redis-test-utils.d.ts +8 -2
  63. package/dist/titan/redis-test-utils.js +147 -92
  64. package/dist/titan/redis-test-utils.js.map +1 -1
  65. package/dist/titan/test-application.d.ts +1 -1
  66. package/dist/titan/test-application.js +1 -1
  67. package/dist/titan/test-application.js.map +1 -1
  68. package/dist/titan/test-fixtures.js.map +1 -1
  69. package/dist/titan/test-mocks.d.ts +12 -11
  70. package/dist/titan/test-mocks.js +49 -49
  71. package/dist/titan/test-mocks.js.map +1 -1
  72. package/dist/titan/test-module.js.map +1 -1
  73. package/package.json +66 -40
  74. package/src/async/events.ts +1 -1
  75. package/src/async/index.ts +5 -30
  76. package/src/async/retry.ts +1 -4
  77. package/src/async/wait.ts +1 -4
  78. package/src/docker/a-port-the-network-could-reach.spec.ts +66 -0
  79. package/src/docker/database-manager.ts +13 -15
  80. package/src/docker/docker-orphan-reaper.spec.ts +175 -0
  81. package/src/docker/docker-port-collision.spec.ts +97 -0
  82. package/src/docker/docker-test-manager.spec.ts +122 -0
  83. package/src/docker/docker-test-manager.ts +421 -327
  84. package/src/docker/docker-volume-cleanup.spec.ts +113 -0
  85. package/src/docker/redis-cluster-creation.spec.ts +52 -0
  86. package/src/docker/redis-manager.ts +87 -117
  87. package/src/docker/types.ts +11 -4
  88. package/src/env.spec.ts +20 -0
  89. package/src/env.ts +33 -0
  90. package/src/errors.ts +9 -2
  91. package/src/globals.d.ts +2 -2
  92. package/src/helpers/assertions.ts +4 -7
  93. package/src/index.ts +1 -1
  94. package/src/runtime/adapter-surface.spec.ts +83 -0
  95. package/src/runtime/bun-adapter.ts +36 -5
  96. package/src/runtime/deno-adapter.ts +167 -108
  97. package/src/runtime/node-adapter.ts +5 -5
  98. package/src/runtime/test-adapter.test.ts +1 -1
  99. package/src/runtime/test-adapter.ts +15 -17
  100. package/src/titan/database/database-testing.module.ts +73 -53
  101. package/src/titan/database/index.ts +2 -2
  102. package/src/titan/database/test-utilities.ts +6 -3
  103. package/src/titan/index.ts +13 -27
  104. package/src/titan/nexus/mock-provider.ts +12 -12
  105. package/src/titan/nexus/test-container.ts +25 -17
  106. package/src/titan/nexus/test-utilities.ts +13 -11
  107. package/src/titan/pm/mock-process-spawner.ts +80 -27
  108. package/src/titan/pm/mock-spawner.ts +10 -4
  109. package/src/titan/pm/test-process-manager.ts +26 -9
  110. package/src/titan/redis-test-utils.test.ts +102 -0
  111. package/src/titan/redis-test-utils.ts +191 -109
  112. package/src/titan/test-application.ts +2 -2
  113. package/src/titan/test-fixtures.ts +0 -1
  114. package/src/titan/test-mocks.ts +50 -50
  115. package/runtime/bun.d.ts +0 -2
  116. package/runtime/bun.js +0 -5
  117. package/runtime/bun.ts +0 -7
  118. package/runtime/deno.d.ts +0 -2
  119. package/runtime/deno.js +0 -4
  120. package/runtime/jest.d.ts +0 -2
  121. package/runtime/jest.js +0 -16
  122. package/runtime/jest.ts +0 -7
@@ -49,15 +49,15 @@ export async function assertRejects(
49
49
  if (expectedError) {
50
50
  if (typeof expectedError === 'string') {
51
51
  if (!error.message.includes(expectedError)) {
52
- throw new Error(`Expected error to include "${expectedError}", got: ${error.message}`);
52
+ throw new Error(`Expected error to include "${expectedError}", got: ${error.message}`, { cause: error });
53
53
  }
54
54
  } else if (expectedError instanceof RegExp) {
55
55
  if (!expectedError.test(error.message)) {
56
- throw new Error(`Expected error to match ${expectedError}, got: ${error.message}`);
56
+ throw new Error(`Expected error to match ${expectedError}, got: ${error.message}`, { cause: error });
57
57
  }
58
58
  } else if (typeof expectedError === 'function') {
59
59
  if (!(error instanceof expectedError)) {
60
- throw new Error(`Expected error to be instance of ${expectedError.name}`);
60
+ throw new Error(`Expected error to be instance of ${expectedError.name}`, { cause: error });
61
61
  }
62
62
  }
63
63
  }
@@ -156,10 +156,7 @@ export interface TestFixture<T> {
156
156
  * });
157
157
  * ```
158
158
  */
159
- export async function withFixture<T, R>(
160
- fixture: TestFixture<T>,
161
- fn: (fixture: T) => R | Promise<R>
162
- ): Promise<R> {
159
+ export async function withFixture<T, R>(fixture: TestFixture<T>, fn: (fixture: T) => R | Promise<R>): Promise<R> {
163
160
  const instance = await fixture.setup();
164
161
  try {
165
162
  return await fn(instance);
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @devgrid/testing - Cross-runtime testing utilities
2
+ * @omnitron-dev/testing - Cross-runtime testing utilities
3
3
  */
4
4
 
5
5
  export * from './runtime/test-adapter.js';
@@ -0,0 +1,83 @@
1
+ /**
2
+ * `loadRuntimeAdapter()` promises one surface across three runtimes. It did not
3
+ * deliver one: bun-adapter exported NOTHING (it only assigned globals) and
4
+ * deno-adapter had no `test`. So the documented `adapter.test(...)` worked on
5
+ * Node and was `undefined is not a function` on Bun — a failure that appears
6
+ * only when someone runs the suite under that runtime, which is exactly the
7
+ * moment the package exists to make cheap.
8
+ *
9
+ * bun-adapter imports `bun:test` and deno-adapter needs Deno globals, so
10
+ * neither can be imported here. The surface is therefore checked statically —
11
+ * with a control below, because a source parser that silently matches nothing
12
+ * would report perfect agreement.
13
+ */
14
+ import { readFileSync } from 'node:fs';
15
+ import { join, dirname } from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ import { describe, it, expect } from 'vitest';
19
+
20
+ const HERE = dirname(fileURLToPath(import.meta.url));
21
+
22
+ /** The names every adapter must expose.
23
+ *
24
+ * `vi` is in the list because a spec doing `import { vi } from 'vitest'` fails
25
+ * to LOAD on a runtime whose adapter lacks it — the whole file is lost before a
26
+ * test runs, which is how `packages/common` had a Deno runner that could not
27
+ * execute a single one of its own specs. Deno's `vi` is built from `mockFn` and
28
+ * `fakeTimers` and covers `fn`, `spyOn` and the timer controls, not all of
29
+ * vitest. */
30
+ const SURFACE = [
31
+ 'describe',
32
+ 'it',
33
+ 'test',
34
+ 'expect',
35
+ 'beforeEach',
36
+ 'afterEach',
37
+ 'beforeAll',
38
+ 'afterAll',
39
+ 'fakeTimers',
40
+ 'vi',
41
+ ] as const;
42
+
43
+ function stripComments(src: string): string {
44
+ return src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/[^\n]*/g, '$1');
45
+ }
46
+
47
+ /** Exported names of a module, from its source. */
48
+ function exportedNames(file: string): Set<string> {
49
+ const src = stripComments(readFileSync(join(HERE, file), 'utf8'));
50
+ const names = new Set<string>();
51
+
52
+ // export const x / export function x / export class x
53
+ for (const m of src.matchAll(/\bexport\s+(?:async\s+)?(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g)) {
54
+ names.add(m[1]!);
55
+ }
56
+ // export { a, b as c } — the alias is the exported name
57
+ for (const block of src.matchAll(/\bexport\s*\{([^}]*)\}/g)) {
58
+ for (const part of block[1]!.split(',')) {
59
+ const t = part.trim();
60
+ if (!t) continue;
61
+ const as = t.match(/\bas\s+([A-Za-z_$][\w$]*)$/);
62
+ names.add(as ? as[1]! : t);
63
+ }
64
+ }
65
+ return names;
66
+ }
67
+
68
+ describe('runtime adapter surface', () => {
69
+ it('the parser can tell present from absent', () => {
70
+ // Without this the checks below pass by finding nothing anywhere.
71
+ const node = exportedNames('node-adapter.ts');
72
+ expect(node.has('expect'), 'parser found no exports at all in node-adapter').toBe(true);
73
+ expect(node.has('definitelyNotExported')).toBe(false);
74
+ });
75
+
76
+ for (const file of ['node-adapter.ts', 'bun-adapter.ts', 'deno-adapter.ts']) {
77
+ it(`${file} exports the whole surface`, () => {
78
+ const names = exportedNames(file);
79
+ const missing = SURFACE.filter((n) => !names.has(n));
80
+ expect(missing, `${file} is missing exports that loadRuntimeAdapter() callers use`).toEqual([]);
81
+ });
82
+ }
83
+ });
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Bun adapter for running Jest tests
3
- * Provides compatibility layer for Jest API
2
+ * Bun adapter for running tests
3
+ * Provides compatibility layer for Vitest API
4
4
  */
5
5
 
6
6
  import {
@@ -16,7 +16,7 @@ import {
16
16
 
17
17
  import { timerUtils } from './test-adapter.js';
18
18
 
19
- // Make Jest-compatible APIs globally available
19
+ // Make test-compatible APIs globally available
20
20
  (global as any).describe = bunDescribe;
21
21
  (global as any).test = bunTest;
22
22
  (global as any).it = bunTest;
@@ -47,10 +47,20 @@ const fakeTimers = {
47
47
  },
48
48
  };
49
49
 
50
- // Mock Jest APIs
51
- (global as any).jest = {
50
+ // Mock vi APIs (Vitest-compatible)
51
+ (global as any).vi = {
52
52
  fn: mock,
53
53
  mock,
54
+ spyOn: (obj: any, method: string) => {
55
+ const original = obj[method];
56
+ const spy = mock(original);
57
+ obj[method] = spy;
58
+ (spy as any).mockRestore = () => {
59
+ obj[method] = original;
60
+ };
61
+ return spy;
62
+ },
63
+ isMockFunction: (fn: any) => typeof fn === 'function' && typeof fn.mock !== 'undefined',
54
64
  useFakeTimers: fakeTimers.useFakeTimers,
55
65
  useRealTimers: fakeTimers.useRealTimers,
56
66
  advanceTimersByTime: fakeTimers.advanceTimersByTime,
@@ -115,3 +125,24 @@ if (!originalExpect.toThrowError) {
115
125
  },
116
126
  });
117
127
  }
128
+
129
+ // ─── Named exports ────────────────────────────────────────────────────────
130
+ //
131
+ // `loadRuntimeAdapter()` hands the caller this module object, so anything not
132
+ // exported here is `undefined` at their call site — not a resolution error, a
133
+ // TypeError one frame later. This file used to export NOTHING: it only assigned
134
+ // globals, so `adapter.test(...)` (the documented usage) worked on Node and
135
+ // threw on Bun. Keep this list in step with node-adapter's; the surface test in
136
+ // adapter-surface.spec.ts fails if it drifts.
137
+ export {
138
+ bunDescribe as describe,
139
+ bunTest as it,
140
+ bunTest as test,
141
+ bunExpect as expect,
142
+ bunBeforeEach as beforeEach,
143
+ bunAfterEach as afterEach,
144
+ bunBeforeAll as beforeAll,
145
+ bunAfterAll as afterAll,
146
+ };
147
+ export { fakeTimers };
148
+ export const vi = (global as any).vi;
@@ -1,14 +1,14 @@
1
1
  /**
2
- * Deno adapter for running Jest tests
3
- * Provides compatibility layer for Jest API
2
+ * Deno adapter for running tests
3
+ * Provides compatibility layer for Vitest API
4
4
  */
5
5
 
6
6
  // @ts-expect-error - Deno specific imports
7
7
  import { FakeTime } from 'https://deno.land/std@0.208.0/testing/time.ts';
8
8
  // @ts-expect-error - Deno specific imports
9
- import { expect as denoExpect } from 'https://deno.land/x/expect@v0.3.0/mod.ts';
9
+ import { expect as denoExpect, addMatchers } from 'https://deno.land/x/expect@v0.3.0/mod.ts';
10
10
  // @ts-expect-error - Deno specific imports
11
- import { it as denoIt, describe as denoDescribe } from 'https://deno.land/std@0.208.0/testing/bdd.ts';
11
+ import { it as denoIt, describe as denoDescribe, beforeAll as denoBeforeAll, beforeEach as denoBeforeEach, afterAll as denoAfterAll, afterEach as denoAfterEach } from 'https://deno.land/std@0.208.0/testing/bdd.ts';
12
12
 
13
13
  // Polyfill for node:util inherits
14
14
  function inherits(ctor: any, superCtor: any) {
@@ -27,77 +27,34 @@ function inherits(ctor: any, superCtor: any) {
27
27
 
28
28
  // Store global state
29
29
  let fakeTime: FakeTime | null = null;
30
- const beforeEachCallbacks: Array<() => void | Promise<void>> = [];
31
- const afterEachCallbacks: Array<() => void | Promise<void>> = [];
32
- const beforeAllCallbacks: Array<() => void | Promise<void>> = [];
33
- const afterAllCallbacks: Array<() => void | Promise<void>> = [];
30
+ /**
31
+ * Lifecycle hooks and blocks delegate to std's bdd, which already scopes hooks
32
+ * to the enclosing `describe`.
33
+ *
34
+ * They used to be four module-level arrays that `it` drained by hand, so a
35
+ * `beforeEach` registered inside one `describe` ran for EVERY test declared
36
+ * afterwards — across files. Concretely: `packages/common`'s
37
+ * `timed-map.spec.ts` installs fake timers in its `beforeEach`, and every
38
+ * later test in the aggregated Deno run inherited them, so `await delay(1)` in
39
+ * a different file never resolved. The run reported all 7 suites passed and
40
+ * then exited 1 with "Promise resolution is still pending but the event loop
41
+ * has already resolved" — an exit code with no failing test attached.
42
+ *
43
+ * `beforeAll` had a second bug in the same code: the callbacks were
44
+ * snapshotted BEFORE the describe body ran, so hooks registered inside the
45
+ * body never executed at all.
46
+ */
47
+ const beforeEach = denoBeforeEach;
48
+ const afterEach = denoAfterEach;
49
+ const beforeAll = denoBeforeAll;
50
+ const afterAll = denoAfterAll;
34
51
 
35
- // Custom describe that handles lifecycle hooks
36
52
  function describe(name: string, fn: () => void) {
37
- denoDescribe(name, () => {
38
- // Clear callbacks for this describe block
39
- // Note: These are preserved for potential future use in nested describe blocks
40
- // const localBeforeEach = [...beforeEachCallbacks];
41
- // const localAfterEach = [...afterEachCallbacks];
42
- const localBeforeAll = [...beforeAllCallbacks];
43
- const localAfterAll = [...afterAllCallbacks];
44
-
45
- // Run beforeAll hooks
46
- if (localBeforeAll.length > 0) {
47
- denoIt('beforeAll', async () => {
48
- for (const cb of localBeforeAll) {
49
- await cb();
50
- }
51
- });
52
- }
53
-
54
- fn();
55
-
56
- // Run afterAll hooks
57
- if (localAfterAll.length > 0) {
58
- denoIt('afterAll', async () => {
59
- for (const cb of localAfterAll) {
60
- await cb();
61
- }
62
- });
63
- }
64
- });
53
+ denoDescribe(name, fn);
65
54
  }
66
55
 
67
- // Custom it/test that runs lifecycle hooks
68
56
  function it(name: string, fn: () => void | Promise<void>) {
69
- denoIt(name, async () => {
70
- // Run beforeEach hooks
71
- for (const cb of beforeEachCallbacks) {
72
- await cb();
73
- }
74
-
75
- try {
76
- await fn();
77
- } finally {
78
- // Run afterEach hooks
79
- for (const cb of afterEachCallbacks) {
80
- await cb();
81
- }
82
- }
83
- });
84
- }
85
-
86
- // Lifecycle hooks
87
- function beforeEach(fn: () => void | Promise<void>) {
88
- beforeEachCallbacks.push(fn);
89
- }
90
-
91
- function afterEach(fn: () => void | Promise<void>) {
92
- afterEachCallbacks.push(fn);
93
- }
94
-
95
- function beforeAll(fn: () => void | Promise<void>) {
96
- beforeAllCallbacks.push(fn);
97
- }
98
-
99
- function afterAll(fn: () => void | Promise<void>) {
100
- afterAllCallbacks.push(fn);
57
+ denoIt(name, fn);
101
58
  }
102
59
 
103
60
  // Mock function implementation
@@ -105,9 +62,14 @@ function mockFn(implementation?: (...args: any[]) => any) {
105
62
  const calls: any[][] = [];
106
63
  const results: any[] = [];
107
64
 
108
- const fn = (...args: any[]) => {
65
+ // `function`, not an arrow, and `.apply` rather than a spread call: a mock
66
+ // must forward `this`. An arrow has no own `this` to forward, so
67
+ // `map.forEach(mock, context)` — or any callback whose contract includes a
68
+ // receiver — silently ran with the wrong one, and the assertion inside the
69
+ // callback failed in a way that pointed at the code under test.
70
+ const fn = function spy(this: any, ...args: any[]) {
109
71
  calls.push(args);
110
- const result = implementation ? implementation(...args) : undefined;
72
+ const result = implementation ? implementation.apply(this, args) : undefined;
111
73
  results.push(result);
112
74
  return result;
113
75
  };
@@ -149,6 +111,10 @@ function mockFn(implementation?: (...args: any[]) => any) {
149
111
  implementation = undefined;
150
112
  };
151
113
 
114
+ fn.mockRestore = () => {
115
+ fn.mockReset();
116
+ };
117
+
152
118
  return fn;
153
119
  }
154
120
 
@@ -183,55 +149,122 @@ const fakeTimers = {
183
149
  },
184
150
  };
185
151
 
186
- // Custom expect wrapper that adds missing methods
187
- const expect = (value: any) => {
188
- const matcher = denoExpect(value);
189
-
190
- // Add missing matcher methods to the chain
191
- matcher.toBeInstanceOf = function toBeInstanceOf(constructor: any) {
192
- const pass = value instanceof constructor;
193
- if (!pass) {
194
- throw new Error(`expected ${value} to be instance of ${constructor.name}`);
195
- }
196
- return { pass };
197
- };
198
-
199
- matcher.toStrictEqual = function toStrictEqual(expected: any) {
200
- return matcher.toEqual(expected);
201
- };
152
+ /**
153
+ * Vitest-shaped mocking surface for Deno.
154
+ *
155
+ * `vi` is what specs written against vitest actually import, and its absence
156
+ * here was the last thing keeping a cross-runtime run from working at all: a
157
+ * spec doing `import { vi } from 'vitest'` fails to LOAD under Deno, taking the
158
+ * whole file with it before a single test runs. Built from the pieces this
159
+ * adapter already had — `mockFn` and `fakeTimers` — so it covers what specs in
160
+ * this monorepo use (`fn`, `spyOn`, and the four timer controls) rather than
161
+ * pretending to be all of vitest.
162
+ */
163
+ const vi = {
164
+ fn: mockFn,
165
+ mock: mockFn,
166
+ spyOn: (obj: any, method: string) => {
167
+ const original = obj[method];
168
+ const spy = mockFn(original);
169
+ obj[method] = spy;
170
+ (spy as any).mockRestore = () => {
171
+ obj[method] = original;
172
+ };
173
+ return spy;
174
+ },
175
+ isMockFunction: (fn: any) => typeof fn === 'function' && typeof (fn as any).mock !== 'undefined',
176
+ useFakeTimers: fakeTimers.useFakeTimers,
177
+ useRealTimers: fakeTimers.useRealTimers,
178
+ advanceTimersByTime: fakeTimers.advanceTimersByTime,
179
+ runAllTimers: fakeTimers.runAllTimers,
180
+ clearAllTimers: fakeTimers.clearAllTimers,
181
+ };
202
182
 
203
- matcher.toThrowError = function toThrowError(expected?: any) {
183
+ /**
184
+ * Call matchers for OUR mocks.
185
+ *
186
+ * `deno.land/x/expect` implements `toHaveBeenCalled*` only for functions made
187
+ * by its own `mock.fn`, and throws "callCount only available on mock
188
+ * functions" for anything else — so a vitest-shaped spec asserting on a
189
+ * callback failed on the matcher rather than on the behaviour. Its `mock.fn`
190
+ * is not a substitute: it drops `this`, which is the bug fixed in `mockFn`
191
+ * below.
192
+ *
193
+ * `addMatchers` is the module's supported extension point and overrides the
194
+ * built-ins. Assigning onto the object returned by `expect(...)` does not:
195
+ * tried first, and the built-in kept winning.
196
+ */
197
+ const callsOf = (v: any): any[][] => (v && v.mock && Array.isArray(v.mock.calls) ? v.mock.calls : []);
198
+ const sameArgs = (a: any[], b: any[]) =>
199
+ a.length === b.length && a.every((x, i) => Deno.inspect(x) === Deno.inspect(b[i]));
200
+
201
+ addMatchers({
202
+ toHaveBeenCalled(value: any) {
203
+ const n = callsOf(value).length;
204
+ return n > 0 ? { pass: true } : { pass: false, message: 'expected mock to have been called' };
205
+ },
206
+ toHaveBeenCalledTimes(value: any, times: number) {
207
+ const n = callsOf(value).length;
208
+ return n === times
209
+ ? { pass: true }
210
+ : { pass: false, message: `expected ${times} call(s), got ${n}` };
211
+ },
212
+ toHaveBeenCalledWith(value: any, ...expected: any[]) {
213
+ const calls = callsOf(value);
214
+ return calls.some((c) => sameArgs(c, expected))
215
+ ? { pass: true }
216
+ : { pass: false, message: `expected a call with ${Deno.inspect(expected)}; calls: ${Deno.inspect(calls)}` };
217
+ },
218
+ toHaveBeenLastCalledWith(value: any, ...expected: any[]) {
219
+ const calls = callsOf(value);
220
+ const last = calls[calls.length - 1];
221
+ return last && sameArgs(last, expected)
222
+ ? { pass: true }
223
+ : { pass: false, message: `last call was ${Deno.inspect(last)}, expected ${Deno.inspect(expected)}` };
224
+ },
225
+ // These three used to be assigned onto the object `expect(...)` returns,
226
+ // which this module ignores — `toStrictEqual` reached a spec as
227
+ // "matcher not found". Same fix, same reason: `addMatchers` is the way in.
228
+ toBeInstanceOf(value: any, constructor: any) {
229
+ return value instanceof constructor
230
+ ? { pass: true }
231
+ : { pass: false, message: `expected ${Deno.inspect(value)} to be instance of ${constructor?.name}` };
232
+ },
233
+ toStrictEqual(value: any, expected: any) {
234
+ return Deno.inspect(value) === Deno.inspect(expected)
235
+ ? { pass: true }
236
+ : { pass: false, message: `expected ${Deno.inspect(value)} to strictly equal ${Deno.inspect(expected)}` };
237
+ },
238
+ toThrowError(value: any, expected?: any) {
204
239
  let error: any;
205
240
  let thrown = false;
206
-
207
241
  try {
208
- if (typeof value === 'function') {
209
- value();
210
- }
242
+ if (typeof value === 'function') value();
211
243
  } catch (e) {
212
244
  error = e;
213
245
  thrown = true;
214
246
  }
215
-
216
- if (!thrown) {
217
- throw new Error('expected function to throw');
218
- }
219
-
247
+ if (!thrown) return { pass: false, message: 'expected function to throw' };
220
248
  if (expected !== undefined) {
221
- if (typeof expected === 'string' && !error.message.includes(expected)) {
222
- throw new Error(`expected error message to include "${expected}"`);
249
+ if (typeof expected === 'string' && !String(error?.message).includes(expected)) {
250
+ return { pass: false, message: `expected error message to include "${expected}"` };
223
251
  }
224
- if (expected instanceof RegExp && !expected.test(error.message)) {
225
- throw new Error(`expected error message to match ${expected}`);
252
+ if (expected instanceof RegExp && !expected.test(String(error?.message))) {
253
+ return { pass: false, message: `expected error message to match ${expected}` };
226
254
  }
227
255
  if (typeof expected === 'function' && !(error instanceof expected)) {
228
- throw new Error(`expected error to be instance of ${expected.name}`);
256
+ return { pass: false, message: `expected error to be instance of ${expected.name}` };
229
257
  }
230
258
  }
231
-
232
259
  return { pass: true };
233
- };
260
+ },
261
+ });
262
+
263
+ // Custom expect wrapper that adds missing methods
264
+ const expect = (value: any) => {
265
+ const matcher = denoExpect(value);
234
266
 
267
+ // Add missing matcher methods to the chain
235
268
  return matcher;
236
269
  };
237
270
 
@@ -250,10 +283,20 @@ expect.extend = (matchers: Record<string, any>) => {
250
283
  (globalThis as any).beforeAll = beforeAll;
251
284
  (globalThis as any).afterAll = afterAll;
252
285
 
253
- // Mock Jest APIs
254
- (globalThis as any).jest = {
286
+ // Mock vi APIs (Vitest-compatible)
287
+ (globalThis as any).vi = {
255
288
  fn: mockFn,
256
289
  mock: mockFn,
290
+ spyOn: (obj: any, method: string) => {
291
+ const original = obj[method];
292
+ const spy = mockFn(original);
293
+ obj[method] = spy;
294
+ spy.mockRestore = () => {
295
+ obj[method] = original;
296
+ };
297
+ return spy;
298
+ },
299
+ isMockFunction: (fn: any) => typeof fn === 'function' && fn.mock !== undefined,
257
300
  useFakeTimers: fakeTimers.useFakeTimers,
258
301
  useRealTimers: fakeTimers.useRealTimers,
259
302
  advanceTimersByTime: fakeTimers.advanceTimersByTime,
@@ -269,4 +312,20 @@ expect.extend = (matchers: Record<string, any>) => {
269
312
  };
270
313
 
271
314
  // Export everything
272
- export { it, expect, mockFn, describe, afterAll, inherits, afterEach, beforeAll, beforeEach };
315
+ // `test` is an alias of `it`, and `fakeTimers` is part of the surface on the
316
+ // other runtimes — see the note in bun-adapter.ts. Absent names come back as
317
+ // `undefined` from `loadRuntimeAdapter()`, never as an import error.
318
+ export {
319
+ it,
320
+ it as test,
321
+ expect,
322
+ mockFn,
323
+ describe,
324
+ afterAll,
325
+ inherits,
326
+ afterEach,
327
+ beforeAll,
328
+ beforeEach,
329
+ fakeTimers,
330
+ vi,
331
+ };
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Node.js adapter for Jest tests
3
- * This is mostly a passthrough since Jest natively runs in Node.js
2
+ * Node.js adapter for Vitest tests
3
+ * This is mostly a passthrough since Vitest natively runs in Node.js
4
4
  */
5
5
 
6
6
  import { timerUtils } from './test-adapter.js';
@@ -26,7 +26,7 @@ export const fakeTimers = {
26
26
  },
27
27
  };
28
28
 
29
- // Re-export Jest globals for consistency with other adapters
29
+ // Re-export Vitest globals for consistency with other adapters
30
30
  export const describe = (global as any).describe;
31
31
  export const it = (global as any).it;
32
32
  export const test = (global as any).test;
@@ -36,5 +36,5 @@ export const afterEach = (global as any).afterEach;
36
36
  export const beforeAll = (global as any).beforeAll;
37
37
  export const afterAll = (global as any).afterAll;
38
38
 
39
- // Re-export Jest object
40
- export const jest = (global as any).jest;
39
+ // Re-export vi object
40
+ export const vi = (global as any).vi;
@@ -48,7 +48,7 @@ describe('test-adapter runtime detection', () => {
48
48
  describe('timer utilities', () => {
49
49
  it('should report fake timers support correctly', () => {
50
50
  const hasFakeTimers = supportsFakeTimers();
51
- if (isNode && typeof (global as any).jest !== 'undefined') {
51
+ if (isNode && typeof (globalThis as any).vi !== 'undefined') {
52
52
  expect(hasFakeTimers).toBe(true);
53
53
  } else {
54
54
  expect(hasFakeTimers).toBe(false);
@@ -12,21 +12,21 @@ export const RUNTIME = (() => {
12
12
  // Timer utilities that work across runtimes
13
13
  export const timerUtils = {
14
14
  useFakeTimers() {
15
- // Only Node.js with Jest supports fake timers
16
- if (RUNTIME === 'node' && typeof (global as any).jest !== 'undefined') {
17
- (global as any).jest.useFakeTimers();
15
+ // Node.js with Vitest supports fake timers via `vi`
16
+ if (RUNTIME === 'node' && typeof (globalThis as any).vi !== 'undefined') {
17
+ (globalThis as any).vi.useFakeTimers();
18
18
  }
19
19
  },
20
20
 
21
21
  useRealTimers() {
22
- if (RUNTIME === 'node' && typeof (global as any).jest !== 'undefined') {
23
- (global as any).jest.useRealTimers();
22
+ if (RUNTIME === 'node' && typeof (globalThis as any).vi !== 'undefined') {
23
+ (globalThis as any).vi.useRealTimers();
24
24
  }
25
25
  },
26
26
 
27
27
  advanceTimersByTime(ms: number) {
28
- if (RUNTIME === 'node' && typeof (global as any).jest !== 'undefined') {
29
- (global as any).jest.advanceTimersByTime(ms);
28
+ if (RUNTIME === 'node' && typeof (globalThis as any).vi !== 'undefined') {
29
+ (globalThis as any).vi.advanceTimersByTime(ms);
30
30
  } else {
31
31
  // For Bun and Deno, we can't advance timers
32
32
  // Tests that rely on this should be skipped or use real timers
@@ -34,14 +34,14 @@ export const timerUtils = {
34
34
  },
35
35
 
36
36
  runAllTimers() {
37
- if (RUNTIME === 'node' && typeof (global as any).jest !== 'undefined') {
38
- (global as any).jest.runAllTimers();
37
+ if (RUNTIME === 'node' && typeof (globalThis as any).vi !== 'undefined') {
38
+ (globalThis as any).vi.runAllTimers();
39
39
  }
40
40
  },
41
41
 
42
42
  clearAllTimers() {
43
- if (RUNTIME === 'node' && typeof (global as any).jest !== 'undefined') {
44
- (global as any).jest.clearAllTimers();
43
+ if (RUNTIME === 'node' && typeof (globalThis as any).vi !== 'undefined') {
44
+ (globalThis as any).vi.clearAllTimers();
45
45
  }
46
46
  },
47
47
 
@@ -71,13 +71,11 @@ export function normalizeGlobalChecks(value: any): boolean {
71
71
  export const isBun = RUNTIME === 'bun';
72
72
  export const isDeno = RUNTIME === 'deno';
73
73
  export const isNode = RUNTIME === 'node';
74
- export const isJest =
75
- isNode &&
76
- typeof (globalThis as any).jest !== 'undefined' &&
77
- typeof (globalThis as any).jest.useFakeTimers === 'function';
74
+ export const isVitest =
75
+ isNode && typeof (globalThis as any).vi !== 'undefined' && typeof (globalThis as any).vi.useFakeTimers === 'function';
78
76
 
79
77
  // Check if fake timers are supported
80
- export const supportsFakeTimers = () => isJest;
78
+ export const supportsFakeTimers = () => isVitest;
81
79
 
82
80
  // Timer utilities
83
81
  export const setupFakeTimers = () => {
@@ -115,7 +113,7 @@ export const expectAsync = async (fn: () => Promise<any>) => {
115
113
  };
116
114
  }
117
115
  } else {
118
- // Jest/Node.js
116
+ // Vitest/Node.js
119
117
  return (globalThis as any).expect(fn()).rejects;
120
118
  }
121
119
  };