ReviewOS

also looking at this

stacks/rpx

test: stop leaking mocked module state across test files

#2274
Merged glennmichael123 wants to merge fix/2270-2271-test-state-leaks into main
8 files +77 -67
packages/rpx/test/cleanup.test.tsmodified+18-13
Changes to packages/rpx/test/cleanup.test.ts
@@ -1,14 +1,17 @@
11import type { CleanupOptions } from '../src/types'
2import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'
2import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'
33import realProcess from 'node:process'
4import * as Hosts from '../src/hosts'
5import * as Https from '../src/https'
46import { cleanup } from '../src/start'
57
68// Mock dependencies
79const mockProcessExit = mock(() => {})
810const mockConsoleLog = mock(() => {})
911const mockConsoleSuccess = mock(() => {})
10const mockRemoveHosts = mock(async () => {})
11const mockCleanupCertificates = mock(async () => {})
12// Spies, not `mock.module`: see the beforeEach below.
13let mockRemoveHosts: any
14let mockCleanupCertificates: any
1215
1316// `mock.module` is global and persists for the rest of the test run. A partial
1417// process replacement ({ exit, on, once, env }) therefore poisons every file
@@ -33,21 +36,23 @@ const processMock = new Proxy(realProcess, {
3336processOverrides.default = processMock
3437mock.module('node:process', () => processMock)
3538
36mock.module('../src/hosts', () => ({
37 removeHosts: mockRemoveHosts,
38}))
39
40mock.module('../src/https', () => ({
41 cleanupCertificates: mockCleanupCertificates,
42}))
43
4439describe('Cleanup Process', () => {
4540 beforeEach(() => {
4641 mockProcessExit.mockClear()
4742 mockConsoleLog.mockClear()
4843 mockConsoleSuccess.mockClear()
49 mockRemoveHosts.mockClear()
50 mockCleanupCertificates.mockClear()
44 // These two were `mock.module('../src/hosts')` / `('../src/https')`, which
45 // replace the whole namespace permanently — `mock.restore()` does not undo a
46 // module mock, so no later file could recover, and each namespace was left
47 // holding a single export (#2270). Spies on the namespace members are
48 // restorable and still observe `cleanup`'s internal calls, the same way
49 // start.test.ts does it.
50 mockRemoveHosts = spyOn(Hosts, 'removeHosts').mockImplementation(async () => {})
51 mockCleanupCertificates = spyOn(Https, 'cleanupCertificates').mockImplementation(async () => {})
52 })
53
54 afterEach(() => {
55 mock.restore()
5156 })
5257
5358 it('should handle multiple cleanup calls gracefully', async () => {