test: gate lanBeacon dgram mock behind a per-suite flag

Same spread+flag pattern as the axios / child_process polluters: the bare
`mock.module('dgram', () => ({ createSocket: () => mockSocket }))` leaked
the stub into every later test file in the run via Bun's last-write-wins
module mock cache. Now we spread real dgram and gate `createSocket`
through `useLanBeaconDgramStubs`, flipped on in beforeAll and off in
afterAll so unrelated UDP-using code in later suites sees real dgram.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
unraid
2026-05-09 16:12:28 +08:00
parent 2bf521ddbe
commit ea5cb3ad02

View File

@@ -1,4 +1,13 @@
import { describe, test, expect, mock, beforeEach, afterEach } from 'bun:test'
import {
afterAll,
afterEach,
beforeAll,
beforeEach,
describe,
expect,
mock,
test,
} from 'bun:test'
// Mock dgram before importing LanBeacon
const mockSocket = {
@@ -13,9 +22,32 @@ const mockSocket = {
close: mock(() => {}),
}
mock.module('dgram', () => ({
createSocket: () => mockSocket,
}))
// Spread+flag pattern: previously this was a bare `mock.module('dgram', ...)`
// which leaked the stub createSocket into every later test file in the
// process via Bun's last-write-wins module mock cache. Spread real dgram
// + gate the stub behind useLanBeaconDgramStubs so other tests see real UDP.
let useLanBeaconDgramStubs = false
mock.module('dgram', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const real = require('dgram') as Record<string, unknown>
return {
...real,
default: real,
createSocket: ((...args: unknown[]) =>
useLanBeaconDgramStubs
? mockSocket
: (real.createSocket as (...a: unknown[]) => unknown)(
...args,
)) as typeof real.createSocket,
}
})
beforeAll(() => {
useLanBeaconDgramStubs = true
})
afterAll(() => {
useLanBeaconDgramStubs = false
})
const { LanBeacon } = await import('../lanBeacon.js')