|
| 1 | +import { describe, afterEach, test, expect, vi } from 'vitest'; |
| 2 | +import cli from './src/cli.js'; |
| 3 | + |
| 4 | +const originalArgv = process.argv; |
| 5 | + |
| 6 | +function setArgv(args: string[]) { |
| 7 | + process.argv = ['node', 'go-git-it', ...args]; |
| 8 | +} |
| 9 | + |
| 10 | +describe('cli', () => { |
| 11 | + afterEach(() => { |
| 12 | + process.argv = originalArgv; |
| 13 | + vi.restoreAllMocks(); |
| 14 | + }); |
| 15 | + |
| 16 | + test('prints help and exits with code 0', () => { |
| 17 | + setArgv([]); |
| 18 | + |
| 19 | + const exitMock = vi |
| 20 | + .spyOn(process, 'exit') |
| 21 | + .mockImplementation(((code?: number) => { |
| 22 | + throw new Error(`process.exit:${code ?? 0}`); |
| 23 | + }) as never); |
| 24 | + const logMock = vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 25 | + |
| 26 | + expect(() => cli(async () => {})).toThrow('process.exit:0'); |
| 27 | + expect(exitMock).toHaveBeenCalledWith(0); |
| 28 | + expect(logMock).toHaveBeenCalled(); |
| 29 | + }); |
| 30 | + |
| 31 | + test('rejects invalid argument counts', () => { |
| 32 | + setArgv(['one', 'two', 'three']); |
| 33 | + |
| 34 | + const exitMock = vi |
| 35 | + .spyOn(process, 'exit') |
| 36 | + .mockImplementation(((code?: number) => { |
| 37 | + throw new Error(`process.exit:${code ?? 0}`); |
| 38 | + }) as never); |
| 39 | + const errorMock = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 40 | + |
| 41 | + expect(() => cli(async () => {})).toThrow('process.exit:1'); |
| 42 | + expect(exitMock).toHaveBeenCalledWith(1); |
| 43 | + expect(errorMock).toHaveBeenCalled(); |
| 44 | + }); |
| 45 | + |
| 46 | + test('invokes goGitIt with provided arguments', async () => { |
| 47 | + setArgv(['https://github.com/owner/repo', './out']); |
| 48 | + |
| 49 | + const exitMock = vi.spyOn(process, 'exit'); |
| 50 | + const goGitIt = vi.fn().mockResolvedValue(undefined); |
| 51 | + |
| 52 | + cli(goGitIt); |
| 53 | + await Promise.resolve(); |
| 54 | + |
| 55 | + expect(goGitIt).toHaveBeenCalledWith( |
| 56 | + 'https://github.com/owner/repo', |
| 57 | + './out', |
| 58 | + ); |
| 59 | + expect(exitMock).not.toHaveBeenCalled(); |
| 60 | + }); |
| 61 | + |
| 62 | + test('prints error and exits on failure', async () => { |
| 63 | + setArgv(['https://github.com/owner/repo']); |
| 64 | + |
| 65 | + const exitMock = vi |
| 66 | + .spyOn(process, 'exit') |
| 67 | + .mockImplementation((() => undefined) as never); |
| 68 | + const errorMock = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 69 | + |
| 70 | + const goGitIt = vi.fn().mockRejectedValue(new Error('boom')); |
| 71 | + |
| 72 | + cli(goGitIt); |
| 73 | + await new Promise<void>((resolve) => { |
| 74 | + setImmediate(resolve); |
| 75 | + }); |
| 76 | + |
| 77 | + expect(exitMock).toHaveBeenCalledWith(1); |
| 78 | + expect(errorMock).toHaveBeenCalled(); |
| 79 | + }); |
| 80 | +}); |
0 commit comments