|
| 1 | +import { readFile } from 'node:fs/promises'; |
| 2 | +import { join } from 'node:path'; |
| 3 | +import anyTest, { TestFn } from 'ava'; |
| 4 | +import { fileExists, runCLI } from '@methodgrab/initializer-utils/testing'; |
| 5 | +import { Answers } from './cli.js'; |
| 6 | + |
| 7 | +const test = anyTest as TestFn<Context>; |
| 8 | + |
| 9 | +type Context = { |
| 10 | + result: Awaited<ReturnType<typeof runCLI>>; |
| 11 | +}; |
| 12 | + |
| 13 | +const answers: Answers = { |
| 14 | + foo: 'test-foo', |
| 15 | + bar: 'test-bar', |
| 16 | + baz: 'test-baz', |
| 17 | +}; |
| 18 | + |
| 19 | +const run = async () => |
| 20 | + await runCLI(new URL('../dist/cli.js', import.meta.url), { |
| 21 | + answers: Object.values(answers), |
| 22 | + }); |
| 23 | + |
| 24 | +test.before('Run the CLI', async t => { |
| 25 | + t.context.result = await run(); |
| 26 | +}); |
| 27 | + |
| 28 | +test.after.always('Clean up temp files', async t => { |
| 29 | + if (t.context.result && typeof t.context.result.cleanup === 'function') { |
| 30 | + await t.context.result.cleanup(); |
| 31 | + } |
| 32 | +}); |
| 33 | + |
| 34 | +test('it creates the expected files', async t => { |
| 35 | + const files = [ |
| 36 | + 'foo.json', |
| 37 | + 'bar.json', |
| 38 | + 'baz.json', |
| 39 | + ]; |
| 40 | + |
| 41 | + for (const file of files) { |
| 42 | + t.true(await fileExists(t.context.result.outputDir, file), `Could not find \`${file}\` in the output dir.`); |
| 43 | + } |
| 44 | +}); |
| 45 | + |
| 46 | +test('it replaces the template variables in the files with the prompt answers', async t => { |
| 47 | + const foo = (await readFileJSON(outputFile(t.context, 'foo.json'))) as Record<string, unknown>; |
| 48 | + t.is(foo.name, answers.foo); |
| 49 | + |
| 50 | + const bar = (await readFileJSON(outputFile(t.context, 'bar.json'))) as Record<string, unknown>; |
| 51 | + t.is(bar.name, answers.bar); |
| 52 | + |
| 53 | + const baz = (await readFileJSON(outputFile(t.context, 'baz.json'))) as Record<string, unknown>; |
| 54 | + t.is(baz.name, answers.baz); |
| 55 | + t.is(baz.custom, true); |
| 56 | +}); |
| 57 | + |
| 58 | +const outputFile = (context: Context, file: string): string => |
| 59 | + join(context.result.outputDir, file); |
| 60 | + |
| 61 | +const readFileString = async (path: string): Promise<string> => |
| 62 | + await readFile(path, 'utf-8'); |
| 63 | + |
| 64 | +const readFileJSON = async (path: string): Promise<unknown> => |
| 65 | + JSON.parse(await readFileString(path)) as unknown; |
0 commit comments