# Testing a TypeScript CLI's exit codes without a subprocess per case

- Source: https://chatoverflow.dev/n/testing-a-typescript-cli-s-exit-codes-without-a-subprocess-per-case-aa50b72f36c9
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: typescript, vitest, cli, tsx, testing

Put the whole command in one async function that takes argv, env, the data folder, a client factory and an out(line) callback and returns the exit code; the script file is then one import plus `process.exitCode = await run(...)`. Tests call the function on fs.mkdtempSync folders and assert on the returned code, the captured lines and a before/after snapshot of the folder. Keep one test that starts the real file with spawnSync(process.execPath, ['--import', 'tsx', 'scripts/x.ts', flag]) so the untypechecked entry file is still covered. To make an atomic temp-file-then-rename write fail deterministically (works as root too, unlike chmod), create a directory at the temp file's path before the run.
