UNPKG

@bomb.sh/tools

Version:

The internal dev, build, and lint CLI for Bombshell projects

1 lines 2.37 kB
{"version":3,"file":"mock.mjs","names":[],"sources":["../../src/test-utils/mock.ts"],"sourcesContent":["import { onTestFinished, vi } from 'vitest';\nimport { MockReadable, MockWritable } from './stdio.ts';\n\ntype InputConfig = true | ConstructorParameters<typeof MockReadable>[0];\ntype OutputConfig = true | ConstructorParameters<typeof MockWritable>[0];\n\nexport interface CreateMockOptions {\n\t/** Environment variables to set for the duration of the test. */\n\tenv?: Record<string, string | undefined>;\n\t/** Pass `true` for defaults, or a config object. Omit to skip. */\n\tinput?: InputConfig;\n\t/** Pass `true` for defaults, or a config object for columns/rows/isTTY. */\n\toutput?: OutputConfig;\n}\n\nexport type Mocks<O extends CreateMockOptions = CreateMockOptions> = {\n\tinput: O['input'] extends InputConfig ? MockReadable : undefined;\n\toutput: O['output'] extends OutputConfig ? MockWritable : undefined;\n};\n\n/**\n * Create a mock test environment with streams, env vars.\n *\n * Cleanup is automatic via `onTestFinished` — no `beforeAll`/`afterAll` needed.\n *\n * @example\n * ```ts\n * let mocks: Mocks;\n * beforeEach(() => {\n * mocks = createMocks({ env: { CI: 'true' }});\n * });\n *\n * it('works', () => {\n * doThing(mocks.input, mocks.output);\n * });\n * ```\n */\nexport function createMocks<O extends CreateMockOptions>(opts?: O): Mocks<O>;\nexport function createMocks(opts: CreateMockOptions = {}): Mocks {\n\tconst input = opts.input\n\t\t? new MockReadable(typeof opts.input === 'object' ? opts.input : undefined)\n\t\t: undefined;\n\tconst output = opts.output\n\t\t? new MockWritable(typeof opts.output === 'object' ? opts.output : undefined)\n\t\t: undefined;\n\tif (opts.env) {\n\t\tfor (const [key, value] of Object.entries(opts.env)) {\n\t\t\tvi.stubEnv(key, value);\n\t\t}\n\t}\n\n\tonTestFinished(() => {\n\t\tvi.unstubAllEnvs();\n\t\tvi.restoreAllMocks();\n\t});\n\n\treturn { input, output } as Mocks;\n}\n"],"mappings":";;;AAsCA,SAAgB,YAAY,OAA0B,CAAC,GAAU;CAChE,MAAM,QAAQ,KAAK,QAChB,IAAI,aAAa,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ,KAAA,CAAS,IACxE,KAAA;CACH,MAAM,SAAS,KAAK,SACjB,IAAI,aAAa,OAAO,KAAK,WAAW,WAAW,KAAK,SAAS,KAAA,CAAS,IAC1E,KAAA;CACH,IAAI,KAAK,KACR,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,GAAG,GACjD,GAAG,QAAQ,KAAK,KAAK;CAIvB,qBAAqB;EACpB,GAAG,cAAc;EACjB,GAAG,gBAAgB;CACpB,CAAC;CAED,OAAO;EAAE;EAAO;CAAO;AACxB"}