|
| 1 | +import { describe, expect, test } from 'bun:test'; |
| 2 | +import type { SpawnOptions } from 'node:child_process'; |
| 3 | +import { spawnDetachedScrubbed } from './detached-spawn.ts'; |
| 4 | + |
| 5 | +describe('spawnDetachedScrubbed', () => { |
| 6 | + interface Captured { |
| 7 | + command?: string; |
| 8 | + args?: readonly string[]; |
| 9 | + opts?: SpawnOptions; |
| 10 | + } |
| 11 | + |
| 12 | + function makeFakeSpawn(captured: Captured, onUnref: () => void) { |
| 13 | + return ((command: string, args: readonly string[], opts: SpawnOptions) => { |
| 14 | + captured.command = command; |
| 15 | + captured.args = args; |
| 16 | + captured.opts = opts; |
| 17 | + return { unref: onUnref }; |
| 18 | + }) as unknown as NonNullable<Parameters<typeof spawnDetachedScrubbed>[2]>['spawn']; |
| 19 | + } |
| 20 | + |
| 21 | + test('spawns detached, stdio:ignore, windowsHide, and unref()s the child', () => { |
| 22 | + const captured: Captured = {}; |
| 23 | + let unrefCalled = false; |
| 24 | + spawnDetachedScrubbed('open', ['-b', 'com.example.app'], { |
| 25 | + spawn: makeFakeSpawn(captured, () => { |
| 26 | + unrefCalled = true; |
| 27 | + }), |
| 28 | + }); |
| 29 | + |
| 30 | + expect(captured.command).toBe('open'); |
| 31 | + expect(captured.args).toEqual(['-b', 'com.example.app']); |
| 32 | + expect(captured.opts?.detached).toBe(true); |
| 33 | + expect(captured.opts?.stdio).toBe('ignore'); |
| 34 | + expect(captured.opts?.windowsHide).toBe(true); |
| 35 | + expect(unrefCalled).toBe(true); |
| 36 | + }); |
| 37 | + |
| 38 | + test('scrubs ELECTRON_RUN_AS_NODE from the child env', () => { |
| 39 | + const captured: Captured = {}; |
| 40 | + spawnDetachedScrubbed('open', ['target'], { |
| 41 | + spawn: makeFakeSpawn(captured, () => {}), |
| 42 | + env: { ELECTRON_RUN_AS_NODE: '1', PATH: '/usr/bin' }, |
| 43 | + }); |
| 44 | + |
| 45 | + expect(captured.opts?.env).toBeDefined(); |
| 46 | + expect(captured.opts?.env).not.toHaveProperty('ELECTRON_RUN_AS_NODE'); |
| 47 | + expect(captured.opts?.env?.PATH).toBe('/usr/bin'); |
| 48 | + }); |
| 49 | + |
| 50 | + test('defaults env to a scrubbed copy of process.env', () => { |
| 51 | + const prevValue = process.env.ELECTRON_RUN_AS_NODE; |
| 52 | + process.env.ELECTRON_RUN_AS_NODE = '1'; |
| 53 | + try { |
| 54 | + const captured: Captured = {}; |
| 55 | + spawnDetachedScrubbed('open', ['target'], { |
| 56 | + spawn: makeFakeSpawn(captured, () => {}), |
| 57 | + }); |
| 58 | + |
| 59 | + expect(captured.opts?.env).not.toHaveProperty('ELECTRON_RUN_AS_NODE'); |
| 60 | + // The scrub copies — this process keeps its own env untouched. |
| 61 | + expect(process.env.ELECTRON_RUN_AS_NODE).toBe('1'); |
| 62 | + } finally { |
| 63 | + if (prevValue === undefined) delete process.env.ELECTRON_RUN_AS_NODE; |
| 64 | + else process.env.ELECTRON_RUN_AS_NODE = prevValue; |
| 65 | + } |
| 66 | + }); |
| 67 | +}); |
0 commit comments