|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | +import { displayLicense } from '../license'; |
| 3 | + |
| 4 | +vi.mock('fs', () => ({ |
| 5 | + readFileSync: vi.fn(), |
| 6 | +})); |
| 7 | + |
| 8 | +describe('displayLicense', () => { |
| 9 | + let logSpy: ReturnType<typeof vi.spyOn>; |
| 10 | + let errorSpy: ReturnType<typeof vi.spyOn>; |
| 11 | + |
| 12 | + beforeEach(() => { |
| 13 | + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 14 | + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 15 | + }); |
| 16 | + |
| 17 | + afterEach(() => { |
| 18 | + logSpy.mockRestore(); |
| 19 | + errorSpy.mockRestore(); |
| 20 | + vi.clearAllMocks(); |
| 21 | + }); |
| 22 | + |
| 23 | + it('prints the license content when LICENSE file is present', async () => { |
| 24 | + const fs = await import('fs'); |
| 25 | + vi.mocked(fs.readFileSync).mockReturnValue('MIT License\nCopyright 2024'); |
| 26 | + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { |
| 27 | + throw new Error('exit'); |
| 28 | + }); |
| 29 | + try { |
| 30 | + displayLicense(); |
| 31 | + } catch { |
| 32 | + // expected if process.exit is called |
| 33 | + } |
| 34 | + expect(fs.readFileSync).toHaveBeenCalled(); |
| 35 | + expect(logSpy).toHaveBeenCalled(); |
| 36 | + const output = logSpy.mock.calls.map(call => call[0]).join('\n'); |
| 37 | + expect(output).toContain('License'); |
| 38 | + expect(output).toContain('MIT License'); |
| 39 | + expect(output).toContain('Copyright 2024'); |
| 40 | + expect(errorSpy).not.toHaveBeenCalled(); |
| 41 | + exitSpy.mockRestore(); |
| 42 | + }); |
| 43 | + |
| 44 | + it('prints an error and fallback license if LICENSE file is missing', async () => { |
| 45 | + const fs = await import('fs'); |
| 46 | + vi.mocked(fs.readFileSync).mockImplementation(() => { |
| 47 | + throw new Error('File not found'); |
| 48 | + }); |
| 49 | + const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { |
| 50 | + throw new Error('exit'); |
| 51 | + }); |
| 52 | + try { |
| 53 | + displayLicense(); |
| 54 | + } catch { |
| 55 | + // expected due to process.exit mock |
| 56 | + } |
| 57 | + expect(errorSpy).toHaveBeenCalled(); |
| 58 | + expect(logSpy).toHaveBeenCalledWith( |
| 59 | + expect.stringContaining('License: MIT') |
| 60 | + ); |
| 61 | + exitSpy.mockRestore(); |
| 62 | + }); |
| 63 | +}); |
0 commit comments