also looking at this
test: stop leaking mocked module state across test files
#2274
8 files
+77
-67
| @@ -1,14 +1,17 @@ | ||
| 1 | 1 | import type { CleanupOptions } from '../src/types' |
| 2 | import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test' | |
| 2 | import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test' | |
| 3 | 3 | import realProcess from 'node:process' |
| 4 | import * as Hosts from '../src/hosts' | |
| 5 | import * as Https from '../src/https' | |
| 4 | 6 | import { cleanup } from '../src/start' |
| 5 | 7 | |
| 6 | 8 | // Mock dependencies |
| 7 | 9 | const mockProcessExit = mock(() => {}) |
| 8 | 10 | const mockConsoleLog = mock(() => {}) |
| 9 | 11 | const mockConsoleSuccess = mock(() => {}) |
| 10 | const mockRemoveHosts = mock(async () => {}) | |
| 11 | const mockCleanupCertificates = mock(async () => {}) | |
| 12 | // Spies, not `mock.module`: see the beforeEach below. | |
| 13 | let mockRemoveHosts: any | |
| 14 | let mockCleanupCertificates: any | |
| 12 | 15 | |
| 13 | 16 | // `mock.module` is global and persists for the rest of the test run. A partial |
| 14 | 17 | // process replacement ({ exit, on, once, env }) therefore poisons every file |
| @@ -33,21 +36,23 @@ const processMock = new Proxy(realProcess, { | ||
| 33 | 36 | processOverrides.default = processMock |
| 34 | 37 | mock.module('node:process', () => processMock) |
| 35 | 38 | |
| 36 | mock.module('../src/hosts', () => ({ | |
| 37 | removeHosts: mockRemoveHosts, | |
| 38 | })) | |
| 39 | ||
| 40 | mock.module('../src/https', () => ({ | |
| 41 | cleanupCertificates: mockCleanupCertificates, | |
| 42 | })) | |
| 43 | ||
| 44 | 39 | describe('Cleanup Process', () => { |
| 45 | 40 | beforeEach(() => { |
| 46 | 41 | mockProcessExit.mockClear() |
| 47 | 42 | mockConsoleLog.mockClear() |
| 48 | 43 | 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() | |
| 51 | 56 | }) |
| 52 | 57 | |
| 53 | 58 | it('should handle multiple cleanup calls gracefully', async () => { |