@react-native-harness/jest 1.2.0-rc.1 → 1.2.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.
Files changed (69) hide show
  1. package/dist/__tests__/bridge.test.d.ts +2 -0
  2. package/dist/__tests__/bridge.test.d.ts.map +1 -0
  3. package/dist/__tests__/bridge.test.js +142 -0
  4. package/dist/__tests__/client-log-handler.test.js +116 -72
  5. package/dist/__tests__/crash-monitor.test.d.ts +2 -0
  6. package/dist/__tests__/crash-monitor.test.d.ts.map +1 -0
  7. package/dist/__tests__/crash-monitor.test.js +212 -0
  8. package/dist/__tests__/execute-run.test.d.ts +2 -0
  9. package/dist/__tests__/execute-run.test.d.ts.map +1 -0
  10. package/dist/__tests__/execute-run.test.js +229 -0
  11. package/dist/__tests__/hook-queue.test.d.ts +2 -0
  12. package/dist/__tests__/hook-queue.test.d.ts.map +1 -0
  13. package/dist/__tests__/hook-queue.test.js +56 -0
  14. package/dist/__tests__/index.test.js +94 -37
  15. package/dist/__tests__/resource-lock.test.js +24 -24
  16. package/dist/client-log-handler.d.ts +10 -11
  17. package/dist/client-log-handler.d.ts.map +1 -1
  18. package/dist/client-log-handler.js +36 -58
  19. package/dist/crash-monitor.d.ts +17 -10
  20. package/dist/crash-monitor.d.ts.map +1 -1
  21. package/dist/crash-monitor.js +164 -63
  22. package/dist/execute-run.d.ts +4 -0
  23. package/dist/execute-run.d.ts.map +1 -0
  24. package/dist/execute-run.js +151 -0
  25. package/dist/harness-session.d.ts +34 -0
  26. package/dist/harness-session.d.ts.map +1 -0
  27. package/dist/harness-session.js +523 -0
  28. package/dist/hook-queue.d.ts +6 -0
  29. package/dist/hook-queue.d.ts.map +1 -0
  30. package/dist/hook-queue.js +18 -0
  31. package/dist/index.d.ts +0 -3
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +12 -230
  34. package/dist/logs.d.ts +1 -0
  35. package/dist/logs.d.ts.map +1 -1
  36. package/dist/logs.js +3 -0
  37. package/dist/resource-lock.d.ts +0 -1
  38. package/dist/resource-lock.d.ts.map +1 -1
  39. package/dist/resource-lock.js +1 -1
  40. package/dist/run.d.ts +2 -2
  41. package/dist/run.d.ts.map +1 -1
  42. package/dist/run.js +3 -3
  43. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  44. package/package.json +7 -8
  45. package/src/__tests__/bridge.test.ts +184 -0
  46. package/src/__tests__/client-log-handler.test.ts +117 -81
  47. package/src/__tests__/crash-monitor.test.ts +288 -0
  48. package/src/__tests__/execute-run.test.ts +325 -0
  49. package/src/__tests__/hook-queue.test.ts +77 -0
  50. package/src/__tests__/index.test.ts +135 -55
  51. package/src/__tests__/resource-lock.test.ts +29 -42
  52. package/src/client-log-handler.ts +48 -64
  53. package/src/crash-monitor.ts +248 -0
  54. package/src/execute-run.ts +199 -0
  55. package/src/harness-session.ts +734 -0
  56. package/src/hook-queue.ts +26 -0
  57. package/src/index.ts +17 -330
  58. package/src/logs.ts +4 -0
  59. package/src/resource-lock.ts +1 -1
  60. package/src/run.ts +5 -5
  61. package/tsconfig.tsbuildinfo +1 -0
  62. package/src/__tests__/crash-supervisor.test.ts +0 -200
  63. package/src/__tests__/harness-cache.test.ts +0 -74
  64. package/src/__tests__/harness.test.ts +0 -923
  65. package/src/crash-supervisor.ts +0 -321
  66. package/src/env.d.ts +0 -9
  67. package/src/harness.ts +0 -870
  68. package/src/setup.ts +0 -127
  69. package/src/teardown.ts +0 -14
@@ -0,0 +1,212 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createCrashMonitor, CrashWatchCancelledError, } from '../crash-monitor.js';
3
+ import { NativeCrashError } from '../errors.js';
4
+ const noop = () => undefined;
5
+ const resolveUndefined = async () => undefined;
6
+ // ---------------------------------------------------------------------------
7
+ // Test doubles
8
+ // ---------------------------------------------------------------------------
9
+ const createAppMonitorMock = () => {
10
+ let registeredListener = null;
11
+ const monitor = {
12
+ start: vi.fn(resolveUndefined),
13
+ stop: vi.fn(resolveUndefined),
14
+ dispose: vi.fn(resolveUndefined),
15
+ addListener: vi.fn((l) => {
16
+ registeredListener = l;
17
+ }),
18
+ removeListener: vi.fn((l) => {
19
+ if (registeredListener === l)
20
+ registeredListener = null;
21
+ }),
22
+ };
23
+ return {
24
+ monitor,
25
+ emit: (event) => registeredListener?.(event),
26
+ };
27
+ };
28
+ const createPlatformRunnerMock = (isRunning = false, crashDetails = null) => ({
29
+ isAppRunning: vi.fn(async () => isRunning),
30
+ getCrashDetails: vi.fn(async () => crashDetails),
31
+ startApp: vi.fn(resolveUndefined),
32
+ restartApp: vi.fn(resolveUndefined),
33
+ stopApp: vi.fn(resolveUndefined),
34
+ dispose: vi.fn(resolveUndefined),
35
+ createAppMonitor: vi.fn(),
36
+ });
37
+ // ---------------------------------------------------------------------------
38
+ // Tests
39
+ // ---------------------------------------------------------------------------
40
+ describe('createCrashMonitor', () => {
41
+ describe('liveness', () => {
42
+ it('starts not alive', () => {
43
+ const { monitor } = createAppMonitorMock();
44
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
45
+ expect(cm.isAlive()).toBe(false);
46
+ });
47
+ it('becomes alive when the app starts', () => {
48
+ const { monitor, emit } = createAppMonitorMock();
49
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
50
+ emit({ type: 'app_started' });
51
+ expect(cm.isAlive()).toBe(true);
52
+ });
53
+ it('becomes not alive after a confirmed crash', async () => {
54
+ const { monitor, emit } = createAppMonitorMock();
55
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
56
+ emit({ type: 'app_started' });
57
+ const watch = cm.watch('test.ts', 'execution');
58
+ watch.promise.catch(noop);
59
+ emit({ type: 'app_exited', isConfirmed: true });
60
+ await watch.promise.catch(noop);
61
+ expect(cm.isAlive()).toBe(false);
62
+ });
63
+ });
64
+ describe('watch', () => {
65
+ it('promise rejects with NativeCrashError on confirmed app_exited', async () => {
66
+ const { monitor, emit } = createAppMonitorMock();
67
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
68
+ const watch = cm.watch('/test/example.ts', 'execution');
69
+ watch.promise.catch(noop);
70
+ emit({ type: 'app_exited', isConfirmed: true });
71
+ await expect(watch.promise).rejects.toBeInstanceOf(NativeCrashError);
72
+ });
73
+ it('attributes the crash to the file and phase passed to watch()', async () => {
74
+ const { monitor, emit } = createAppMonitorMock();
75
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
76
+ const watch = cm.watch('/test/example.ts', 'startup');
77
+ watch.promise.catch(noop);
78
+ emit({ type: 'app_exited', isConfirmed: true });
79
+ const error = await watch.promise.catch((e) => e);
80
+ expect(error.testFilePath).toBe('/test/example.ts');
81
+ expect(error.details.phase).toBe('startup');
82
+ });
83
+ it('settles the promise with CrashWatchCancelledError on cancel()', async () => {
84
+ const { monitor } = createAppMonitorMock();
85
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
86
+ const watch = cm.watch('test.ts', 'execution');
87
+ watch.cancel();
88
+ await expect(watch.promise).rejects.toBeInstanceOf(CrashWatchCancelledError);
89
+ });
90
+ it('subsequent cancel() after crash is a no-op', async () => {
91
+ const { monitor, emit } = createAppMonitorMock();
92
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
93
+ const watch = cm.watch('test.ts', 'execution');
94
+ watch.promise.catch(noop);
95
+ emit({ type: 'app_exited', isConfirmed: true });
96
+ await watch.promise.catch(noop);
97
+ // Second cancel should not throw or cause issues.
98
+ expect(() => watch.cancel()).not.toThrow();
99
+ });
100
+ });
101
+ describe('unconfirmed events', () => {
102
+ it('fires the crash if isAppRunning returns false', async () => {
103
+ const { monitor, emit } = createAppMonitorMock();
104
+ const runner = createPlatformRunnerMock(false /* not running */);
105
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: runner });
106
+ const watch = cm.watch('test.ts', 'execution');
107
+ watch.promise.catch(noop);
108
+ emit({ type: 'app_exited', isConfirmed: false });
109
+ await expect(watch.promise).rejects.toBeInstanceOf(NativeCrashError);
110
+ });
111
+ it('does not fire if isAppRunning returns true', async () => {
112
+ const { monitor, emit } = createAppMonitorMock();
113
+ const runner = createPlatformRunnerMock(true /* still running */);
114
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: runner });
115
+ const watch = cm.watch('test.ts', 'execution');
116
+ const settled = vi.fn();
117
+ watch.promise.then(settled, settled);
118
+ emit({ type: 'app_exited', isConfirmed: false });
119
+ await new Promise((r) => setTimeout(r, 20));
120
+ expect(settled).not.toHaveBeenCalled();
121
+ watch.cancel();
122
+ });
123
+ it('fires on possible_crash when confirmed', async () => {
124
+ const { monitor, emit } = createAppMonitorMock();
125
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
126
+ const watch = cm.watch('test.ts', 'execution');
127
+ watch.promise.catch(noop);
128
+ emit({ type: 'possible_crash', isConfirmed: true });
129
+ await expect(watch.promise).rejects.toBeInstanceOf(NativeCrashError);
130
+ });
131
+ });
132
+ describe('crash detail enrichment', () => {
133
+ it('merges initial and enriched crash details', async () => {
134
+ const { monitor, emit } = createAppMonitorMock();
135
+ const runner = createPlatformRunnerMock(false, {
136
+ processName: 'MyApp',
137
+ signal: 'SIGSEGV',
138
+ summary: 'Segmentation fault',
139
+ });
140
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: runner });
141
+ const watch = cm.watch('test.ts', 'execution');
142
+ watch.promise.catch(noop);
143
+ emit({ type: 'app_exited', isConfirmed: true, crashDetails: { pid: 1234 } });
144
+ const error = await watch.promise.catch((e) => e);
145
+ expect(error.details.processName).toBe('MyApp');
146
+ expect(error.details.signal).toBe('SIGSEGV');
147
+ expect(error.details.pid).toBe(1234);
148
+ });
149
+ });
150
+ describe('stop / start', () => {
151
+ it('ignores events while stopped', async () => {
152
+ const { monitor, emit } = createAppMonitorMock();
153
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
154
+ await cm.stop();
155
+ const watch = cm.watch('test.ts', 'execution');
156
+ const settled = vi.fn();
157
+ watch.promise.then(settled, settled);
158
+ emit({ type: 'app_exited', isConfirmed: true });
159
+ await new Promise((r) => setTimeout(r, 10));
160
+ expect(settled).not.toHaveBeenCalled();
161
+ watch.cancel();
162
+ });
163
+ it('resumes monitoring after start()', async () => {
164
+ const { monitor, emit } = createAppMonitorMock();
165
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
166
+ await cm.stop();
167
+ await cm.start();
168
+ const watch = cm.watch('test.ts', 'execution');
169
+ watch.promise.catch(noop);
170
+ emit({ type: 'app_exited', isConfirmed: true });
171
+ await expect(watch.promise).rejects.toBeInstanceOf(NativeCrashError);
172
+ });
173
+ });
174
+ describe('reset', () => {
175
+ it('clears alive state and pending watchers', async () => {
176
+ const { monitor, emit } = createAppMonitorMock();
177
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
178
+ emit({ type: 'app_started' });
179
+ const watch = cm.watch('test.ts', 'execution');
180
+ watch.promise.catch(noop);
181
+ cm.reset();
182
+ expect(cm.isAlive()).toBe(false);
183
+ // The watcher was cleared; a crash fired now should not reach the old watch.
184
+ emit({ type: 'app_exited', isConfirmed: true });
185
+ await new Promise((r) => setTimeout(r, 10));
186
+ // Old promise is still pending (we can verify by cancel resolving it).
187
+ watch.cancel();
188
+ await expect(watch.promise).rejects.toBeInstanceOf(CrashWatchCancelledError);
189
+ });
190
+ });
191
+ describe('dispose', () => {
192
+ it('ignores events after dispose', async () => {
193
+ const { monitor, emit } = createAppMonitorMock();
194
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
195
+ const watch = cm.watch('test.ts', 'execution');
196
+ watch.promise.catch(noop);
197
+ await cm.dispose();
198
+ emit({ type: 'app_exited', isConfirmed: true });
199
+ await new Promise((r) => setTimeout(r, 10));
200
+ // After dispose watchers are cleared, so crash didn't propagate.
201
+ // The promise is still pending - cancel to settle it.
202
+ watch.cancel();
203
+ await expect(watch.promise).rejects.toBeInstanceOf(CrashWatchCancelledError);
204
+ });
205
+ it('calls appMonitor.dispose()', async () => {
206
+ const { monitor } = createAppMonitorMock();
207
+ const cm = createCrashMonitor({ appMonitor: monitor, platformRunner: createPlatformRunnerMock() });
208
+ await cm.dispose();
209
+ expect(monitor.dispose).toHaveBeenCalledOnce();
210
+ });
211
+ });
212
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=execute-run.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execute-run.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/execute-run.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,229 @@
1
+ import { describe, expect, it, vi, beforeEach } from 'vitest';
2
+ import { NativeCrashError, StartupStallError } from '../errors.js';
3
+ import { DeviceNotRespondingError } from '@react-native-harness/bridge/server';
4
+ import { executeRun } from '../execute-run.js';
5
+ const resolveUndefined = async () => undefined;
6
+ // Mock the file-runner so we control what jestResult/harnessResult each test returns
7
+ // without needing a real Jest config or Metro bundler.
8
+ const mockRunHarnessTestFile = vi.hoisted(() => vi.fn());
9
+ vi.mock('../run.js', () => ({
10
+ runHarnessTestFile: mockRunHarnessTestFile,
11
+ }));
12
+ // ---------------------------------------------------------------------------
13
+ // Helpers
14
+ // ---------------------------------------------------------------------------
15
+ const makeJestResult = (overrides = {}) => ({
16
+ testFilePath: '/test/example.ts',
17
+ testResults: [],
18
+ failureMessage: null,
19
+ numFailingTests: 0,
20
+ numPassingTests: 1,
21
+ numPendingTests: 0,
22
+ numTodoTests: 0,
23
+ leaks: false,
24
+ openHandles: [],
25
+ skipped: false,
26
+ snapshot: {
27
+ added: 0, fileDeleted: false, matched: 0, unchecked: 0,
28
+ uncheckedKeys: [], unmatched: 0, updated: 0,
29
+ },
30
+ perfStats: { start: 0, end: 1, runtime: 1, slow: false,
31
+ loadTestEnvironmentStart: 0, loadTestEnvironmentEnd: 0,
32
+ setupAfterEnvStart: 0, setupAfterEnvEnd: 0,
33
+ setupFilesStart: 0, setupFilesEnd: 0 },
34
+ coverage: undefined,
35
+ ...overrides,
36
+ });
37
+ const makeHarnessResult = (status = 'passed') => ({
38
+ name: 'suite',
39
+ tests: [],
40
+ suites: [],
41
+ status,
42
+ duration: 50,
43
+ });
44
+ const makeFileRunResult = (overrides = {}) => ({
45
+ jestResult: makeJestResult(),
46
+ harnessResult: makeHarnessResult(),
47
+ relativeTestPath: 'example.ts',
48
+ duration: 50,
49
+ ...overrides,
50
+ });
51
+ const makeTest = (filePath = '/test/example.ts') => ({
52
+ path: filePath,
53
+ context: { config: {} },
54
+ });
55
+ const makeWatcher = (interrupted = false) => ({ isInterrupted: () => interrupted });
56
+ const makeGlobalConfig = (overrides = {}) => ({
57
+ rootDir: '/project',
58
+ watch: false,
59
+ watchAll: false,
60
+ collectCoverage: false,
61
+ ...overrides,
62
+ });
63
+ const makeSession = (overrides = {}) => ({
64
+ config: {
65
+ metroPort: 8081,
66
+ host: undefined,
67
+ resetEnvironmentBetweenTestFiles: false,
68
+ detectNativeCrashes: true,
69
+ },
70
+ context: {},
71
+ ensureAppReady: vi.fn(resolveUndefined),
72
+ runTestFile: vi.fn(async () => makeHarnessResult()),
73
+ restartApp: vi.fn(resolveUndefined),
74
+ resetCrashState: vi.fn(),
75
+ flushClientLogs: vi.fn(() => []),
76
+ callHook: vi.fn(resolveUndefined),
77
+ setRunState: vi.fn(),
78
+ dispose: vi.fn(resolveUndefined),
79
+ ...overrides,
80
+ });
81
+ // ---------------------------------------------------------------------------
82
+ // Tests
83
+ // ---------------------------------------------------------------------------
84
+ beforeEach(() => {
85
+ vi.clearAllMocks();
86
+ mockRunHarnessTestFile.mockResolvedValue(makeFileRunResult());
87
+ });
88
+ describe('executeRun', () => {
89
+ describe('lifecycle hooks', () => {
90
+ it('emits run:started then run:finished in order', async () => {
91
+ const hookNames = [];
92
+ const session = makeSession({
93
+ callHook: vi.fn(async (name) => { hookNames.push(name); }),
94
+ });
95
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
96
+ expect(hookNames[0]).toBe('run:started');
97
+ expect(hookNames[hookNames.length - 1]).toBe('run:finished');
98
+ });
99
+ it('emits test-file:started and test-file:finished around each test', async () => {
100
+ const hookNames = [];
101
+ const session = makeSession({
102
+ callHook: vi.fn(async (name) => { hookNames.push(name); }),
103
+ });
104
+ await executeRun(session, [makeTest('/a.ts'), makeTest('/b.ts')], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
105
+ const fileHooks = hookNames.filter((n) => n === 'test-file:started' || n === 'test-file:finished');
106
+ expect(fileHooks).toEqual([
107
+ 'test-file:started', 'test-file:finished',
108
+ 'test-file:started', 'test-file:finished',
109
+ ]);
110
+ });
111
+ it('always emits run:finished even when a test throws', async () => {
112
+ const hookNames = [];
113
+ const session = makeSession({
114
+ callHook: vi.fn(async (name) => { hookNames.push(name); }),
115
+ ensureAppReady: vi.fn(async () => { throw new Error('unexpected'); }),
116
+ });
117
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
118
+ expect(hookNames).toContain('run:finished');
119
+ });
120
+ });
121
+ describe('happy path', () => {
122
+ it('calls onStart, ensureAppReady, runTestFile, onResult in order', async () => {
123
+ const order = [];
124
+ const session = makeSession({
125
+ ensureAppReady: vi.fn(async () => { order.push('ensureAppReady'); }),
126
+ });
127
+ const onStart = vi.fn(async () => { order.push('onStart'); });
128
+ const onResult = vi.fn(async () => { order.push('onResult'); });
129
+ mockRunHarnessTestFile.mockImplementation(async () => {
130
+ order.push('runTestFile');
131
+ return makeFileRunResult();
132
+ });
133
+ await executeRun(session, [makeTest()], makeWatcher(), onStart, onResult, vi.fn(), makeGlobalConfig());
134
+ expect(order).toEqual(['onStart', 'ensureAppReady', 'runTestFile', 'onResult']);
135
+ });
136
+ it('accumulates passing test counts in run:finished summary', async () => {
137
+ let finishedPayload;
138
+ const session = makeSession({
139
+ callHook: vi.fn(async (name, payload) => {
140
+ if (name === 'run:finished')
141
+ finishedPayload = payload;
142
+ }),
143
+ });
144
+ mockRunHarnessTestFile.mockResolvedValue(makeFileRunResult({ jestResult: makeJestResult({ numPassingTests: 3 }) }));
145
+ await executeRun(session, [makeTest(), makeTest('/b.ts')], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
146
+ const payload = finishedPayload;
147
+ expect(payload.summary.passed).toBe(6);
148
+ expect(payload.status).toBe('passed');
149
+ });
150
+ it('attaches buffered client logs to the Jest result', async () => {
151
+ const clientLogs = [{ message: 'Loaded screen', origin: '', type: 'warn' }];
152
+ const session = makeSession({
153
+ flushClientLogs: vi.fn()
154
+ .mockReturnValueOnce([])
155
+ .mockReturnValueOnce(clientLogs),
156
+ });
157
+ const onResult = vi.fn();
158
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), onResult, vi.fn(), makeGlobalConfig());
159
+ expect(session.flushClientLogs).toHaveBeenCalledTimes(2);
160
+ expect(onResult).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ console: clientLogs }));
161
+ });
162
+ });
163
+ describe('runtime failures', () => {
164
+ it('passes StartupStallError to onFailure with an empty stack', async () => {
165
+ const onFailure = vi.fn();
166
+ const session = makeSession({
167
+ ensureAppReady: vi.fn().mockRejectedValue(new StartupStallError(1500, 3)),
168
+ });
169
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), onFailure, makeGlobalConfig());
170
+ expect(onFailure).toHaveBeenCalledWith(expect.objectContaining({ path: '/test/example.ts' }), expect.objectContaining({ message: expect.stringContaining('1500'), stack: '' }));
171
+ });
172
+ it('passes DeviceNotRespondingError to onFailure with an empty stack', async () => {
173
+ const onFailure = vi.fn();
174
+ const session = makeSession({
175
+ ensureAppReady: vi.fn().mockRejectedValue(new DeviceNotRespondingError('runTests', [])),
176
+ });
177
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), onFailure, makeGlobalConfig());
178
+ expect(onFailure).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ stack: '' }));
179
+ });
180
+ it('calls resetCrashState after a NativeCrashError', async () => {
181
+ const session = makeSession({
182
+ ensureAppReady: vi.fn().mockRejectedValue(new NativeCrashError('example.ts', { phase: 'execution', source: 'polling' })),
183
+ });
184
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
185
+ expect(session.resetCrashState).toHaveBeenCalled();
186
+ });
187
+ it('counts runtime failures in the summary', async () => {
188
+ let finishedPayload;
189
+ const session = makeSession({
190
+ callHook: vi.fn(async (name, payload) => {
191
+ if (name === 'run:finished')
192
+ finishedPayload = payload;
193
+ }),
194
+ ensureAppReady: vi.fn().mockRejectedValue(new StartupStallError(1000, 2)),
195
+ });
196
+ await executeRun(session, [makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
197
+ const payload = finishedPayload;
198
+ expect(payload.summary.failed).toBe(1);
199
+ expect(payload.status).toBe('failed');
200
+ });
201
+ });
202
+ describe('watcher interrupt', () => {
203
+ it('stops processing tests and still emits run:finished', async () => {
204
+ const hookNames = [];
205
+ const session = makeSession({
206
+ callHook: vi.fn(async (name) => { hookNames.push(name); }),
207
+ });
208
+ const onStart = vi.fn();
209
+ await executeRun(session, [makeTest('/a.ts'), makeTest('/b.ts')], makeWatcher(true /* interrupted */), onStart, vi.fn(), vi.fn(), makeGlobalConfig());
210
+ // No test was started; watcher was already interrupted.
211
+ expect(onStart).not.toHaveBeenCalled();
212
+ expect(hookNames).toContain('run:finished');
213
+ });
214
+ });
215
+ describe('resetEnvironmentBetweenTestFiles', () => {
216
+ it('calls restartApp before the second test but not the first', async () => {
217
+ const session = makeSession({
218
+ config: {
219
+ metroPort: 8081,
220
+ resetEnvironmentBetweenTestFiles: true,
221
+ detectNativeCrashes: false,
222
+ },
223
+ });
224
+ await executeRun(session, [makeTest('/a.ts'), makeTest('/b.ts'), makeTest('/c.ts')], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeGlobalConfig());
225
+ // restartApp should be called for tests 2 and 3, not test 1.
226
+ expect(session.restartApp).toHaveBeenCalledTimes(2);
227
+ });
228
+ });
229
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=hook-queue.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook-queue.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/hook-queue.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createHookQueue } from '../hook-queue.js';
3
+ describe('createHookQueue', () => {
4
+ it('executes scheduled work in FIFO order', async () => {
5
+ const queue = createHookQueue();
6
+ const order = [];
7
+ queue.schedule(async () => { order.push(1); });
8
+ queue.schedule(async () => { order.push(2); });
9
+ queue.schedule(async () => { order.push(3); });
10
+ await queue.drain();
11
+ expect(order).toEqual([1, 2, 3]);
12
+ });
13
+ it('drain awaits async work before resolving', async () => {
14
+ const queue = createHookQueue();
15
+ let resolved = false;
16
+ queue.schedule(async () => {
17
+ await new Promise((r) => setTimeout(r, 20));
18
+ resolved = true;
19
+ });
20
+ expect(resolved).toBe(false);
21
+ await queue.drain();
22
+ expect(resolved).toBe(true);
23
+ });
24
+ it('drain resolves immediately when nothing is scheduled', async () => {
25
+ const queue = createHookQueue();
26
+ await expect(queue.drain()).resolves.toBeUndefined();
27
+ });
28
+ it('captures the first error and re-throws it on drain', async () => {
29
+ const queue = createHookQueue();
30
+ const err = new Error('hook failed');
31
+ queue.schedule(async () => { throw err; });
32
+ await expect(queue.drain()).rejects.toBe(err);
33
+ });
34
+ it('continues executing subsequent hooks after one throws', async () => {
35
+ const queue = createHookQueue();
36
+ const ran = [];
37
+ queue.schedule(async () => { throw new Error('first'); });
38
+ queue.schedule(async () => { ran.push('second'); });
39
+ queue.schedule(async () => { ran.push('third'); });
40
+ await expect(queue.drain()).rejects.toThrow('first');
41
+ expect(ran).toEqual(['second', 'third']);
42
+ });
43
+ it('error is cleared after drain re-throws it', async () => {
44
+ const queue = createHookQueue();
45
+ queue.schedule(async () => { throw new Error('once'); });
46
+ await expect(queue.drain()).rejects.toThrow('once');
47
+ // Second drain should see no accumulated error.
48
+ await expect(queue.drain()).resolves.toBeUndefined();
49
+ });
50
+ it('surfaces only the first error when multiple hooks throw', async () => {
51
+ const queue = createHookQueue();
52
+ queue.schedule(async () => { throw new Error('first'); });
53
+ queue.schedule(async () => { throw new Error('second'); });
54
+ await expect(queue.drain()).rejects.toThrow('first');
55
+ });
56
+ });
@@ -1,42 +1,99 @@
1
- import { describe, expect, it, vi } from 'vitest';
1
+ import { describe, expect, it, vi, beforeEach } from 'vitest';
2
+ import { HarnessError } from '@react-native-harness/tools';
2
3
  import JestHarness from '../index.js';
3
- import { StartupStallError } from '../errors.js';
4
+ const resolveUndefined = async () => undefined;
5
+ // ---------------------------------------------------------------------------
6
+ // Module mocks
7
+ // ---------------------------------------------------------------------------
8
+ const mockSession = {
9
+ config: { metroPort: 8081 },
10
+ context: {},
11
+ ensureAppReady: vi.fn(resolveUndefined),
12
+ runTestFile: vi.fn(async () => ({
13
+ name: '',
14
+ tests: [],
15
+ suites: [],
16
+ status: 'passed',
17
+ duration: 0,
18
+ })),
19
+ restartApp: vi.fn(resolveUndefined),
20
+ resetCrashState: vi.fn(),
21
+ flushClientLogs: vi.fn(() => []),
22
+ callHook: vi.fn(resolveUndefined),
23
+ setRunState: vi.fn(),
24
+ dispose: vi.fn(resolveUndefined),
25
+ };
26
+ const mockCreateHarnessSession = vi.hoisted(() => vi.fn(async () => mockSession));
27
+ const mockExecuteRun = vi.hoisted(() => vi.fn(async () => undefined));
28
+ vi.mock('../harness-session.js', () => ({
29
+ createHarnessSession: mockCreateHarnessSession,
30
+ }));
31
+ vi.mock('../execute-run.js', () => ({
32
+ executeRun: mockExecuteRun,
33
+ }));
34
+ // ---------------------------------------------------------------------------
35
+ // Helpers
36
+ // ---------------------------------------------------------------------------
37
+ const makeOptions = () => ({ serial: true });
38
+ const makeWatcher = () => ({ isInterrupted: () => false });
39
+ const makeTest = () => ({
40
+ path: '/test/example.ts',
41
+ context: { config: {} },
42
+ });
43
+ const makeGlobalConfig = (overrides = {}) => ({ rootDir: '/project', watch: false, watchAll: false, collectCoverage: false, ...overrides });
44
+ // ---------------------------------------------------------------------------
45
+ // Tests
46
+ // ---------------------------------------------------------------------------
47
+ beforeEach(() => {
48
+ vi.clearAllMocks();
49
+ mockSession.dispose.mockResolvedValue(undefined);
50
+ mockExecuteRun.mockResolvedValue(undefined);
51
+ mockCreateHarnessSession.mockResolvedValue(mockSession);
52
+ });
4
53
  describe('JestHarness', () => {
5
- it('reports StartupStallError without a stack trace', async () => {
6
- const runner = new JestHarness({});
7
- const onFailure = vi.fn();
8
- const harness = {
9
- ensureAppReady: vi
10
- .fn()
11
- .mockRejectedValue(new StartupStallError(1500, 3)),
12
- callHook: vi.fn(async () => undefined),
13
- setRunState: vi.fn(),
14
- getRunState: vi.fn(() => null),
15
- crashSupervisor: {
16
- beginTestRun: vi.fn(),
17
- waitForCrash: vi.fn(),
18
- cancelCrashWaiters: vi.fn(),
19
- reset: vi.fn(),
20
- },
21
- };
22
- await runner._createInBandTestRun([
23
- {
24
- path: '/tmp/example.harness.ts',
25
- context: {
26
- config: {},
27
- },
28
- },
29
- ], {
30
- isInterrupted: () => false,
31
- }, harness, {
32
- detectNativeCrashes: true,
33
- resetEnvironmentBetweenTestFiles: false,
34
- }, () => Promise.resolve(), () => Promise.resolve(), onFailure);
35
- expect(onFailure).toHaveBeenCalledWith(expect.objectContaining({
36
- path: '/tmp/example.harness.ts',
37
- }), {
38
- message: 'The app did not request its Metro bundle after 3 launch attempts within 1500ms. Last Metro status: unknown.',
39
- stack: '',
54
+ describe('session lifecycle', () => {
55
+ it('creates a session on the first run', async () => {
56
+ const runner = new JestHarness(makeGlobalConfig());
57
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
58
+ expect(mockCreateHarnessSession).toHaveBeenCalledOnce();
59
+ });
60
+ it('reuses the session across runs in watch mode', async () => {
61
+ const runner = new JestHarness(makeGlobalConfig({ watch: true }));
62
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
63
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
64
+ expect(mockCreateHarnessSession).toHaveBeenCalledOnce();
65
+ expect(mockSession.dispose).not.toHaveBeenCalled();
66
+ });
67
+ it('disposes the session after each run in normal mode', async () => {
68
+ const runner = new JestHarness(makeGlobalConfig());
69
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
70
+ expect(mockSession.dispose).toHaveBeenCalledOnce();
71
+ });
72
+ it('creates a fresh session for each run in normal mode', async () => {
73
+ const runner = new JestHarness(makeGlobalConfig());
74
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
75
+ await runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions());
76
+ expect(mockCreateHarnessSession).toHaveBeenCalledTimes(2);
77
+ });
78
+ });
79
+ describe('error handling', () => {
80
+ it('converts HarnessError into a formatted string before throwing', async () => {
81
+ class TestHarnessError extends HarnessError {
82
+ constructor() { super('something went wrong'); this.name = 'TestHarnessError'; }
83
+ }
84
+ mockCreateHarnessSession.mockRejectedValue(new TestHarnessError());
85
+ const runner = new JestHarness(makeGlobalConfig());
86
+ await expect(runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions())).rejects.toBeTypeOf('string');
87
+ });
88
+ it('propagates non-HarnessError exceptions as-is', async () => {
89
+ const cause = new TypeError('unexpected');
90
+ mockCreateHarnessSession.mockRejectedValue(cause);
91
+ const runner = new JestHarness(makeGlobalConfig());
92
+ await expect(runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), makeOptions())).rejects.toBe(cause);
93
+ });
94
+ it('throws when called without serial flag', async () => {
95
+ const runner = new JestHarness(makeGlobalConfig());
96
+ await expect(runner.runTests([makeTest()], makeWatcher(), vi.fn(), vi.fn(), vi.fn(), { serial: false })).rejects.toThrow('Parallel test running is not supported');
40
97
  });
41
98
  });
42
99
  });