|
| 1 | +import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest' |
| 2 | +import { logger } from '../src/logger' |
| 3 | + |
| 4 | +describe('logger', () => { |
| 5 | + const originalConsole = console |
| 6 | + let spies: Record<'log' | 'error' | 'warn', ReturnType<typeof vi.fn>> |
| 7 | + |
| 8 | + const expected = { |
| 9 | + log: 0, |
| 10 | + error: 31, |
| 11 | + warn: 33, |
| 12 | + } as const |
| 13 | + |
| 14 | + beforeEach(() => { |
| 15 | + spies = { |
| 16 | + log: vi.fn(), |
| 17 | + error: vi.fn(), |
| 18 | + warn: vi.fn(), |
| 19 | + } |
| 20 | + |
| 21 | + console = { |
| 22 | + ...originalConsole, |
| 23 | + ...(spies as any), |
| 24 | + } |
| 25 | + }) |
| 26 | + |
| 27 | + afterEach(() => { |
| 28 | + console = originalConsole |
| 29 | + }) |
| 30 | + |
| 31 | + beforeAll(() => { |
| 32 | + logger.enabled = true |
| 33 | + }) |
| 34 | + |
| 35 | + test('appends time properly', () => { |
| 36 | + logger.log('test') |
| 37 | + const args = spies.log.mock.calls[0] |
| 38 | + const joined = args.join(' ') |
| 39 | + const timeIdx = 4 |
| 40 | + const timeStr = joined.slice(timeIdx, timeIdx + 8) |
| 41 | + expect(timeStr).toMatch(/^\d{2}:\d{2}:\d{2}$/) |
| 42 | + }) |
| 43 | + |
| 44 | + describe('colors', () => { |
| 45 | + test('colors prefix properly', () => { |
| 46 | + const prefix = logger.prefix |
| 47 | + logger.log('test') |
| 48 | + const args = spies.log.mock.calls[0] |
| 49 | + const joined = args.join(' ') |
| 50 | + const prefixIdx = joined.indexOf(prefix) |
| 51 | + const prefixColorIdx = prefixIdx - 6 |
| 52 | + |
| 53 | + expect(prefixIdx).not.toBe(-1) |
| 54 | + expect(joined.slice(prefixColorIdx, prefixColorIdx + prefix.length)).toBe('\x1b[34m[') |
| 55 | + }) |
| 56 | + |
| 57 | + test('colors time properly', () => { |
| 58 | + logger.log('test') |
| 59 | + const args = spies.log.mock.calls[0] |
| 60 | + originalConsole.log('ARGS: ', JSON.stringify(spies.log.mock.calls)) |
| 61 | + const joined = args.join(' ') |
| 62 | + const timeColorIdx = 0 |
| 63 | + expect(joined.slice(timeColorIdx, timeColorIdx + 4)).toBe('\x1b[2m') |
| 64 | + }) |
| 65 | + |
| 66 | + for (const type of ['error', 'warn'] as const) { |
| 67 | + test(`colors ${type} properly`, () => { |
| 68 | + logger[type]('test') |
| 69 | + const args = spies[type].mock.calls[0] |
| 70 | + const joined = args.join(' ') |
| 71 | + const typeIdx = joined.indexOf(type.toUpperCase()) |
| 72 | + const typeColorIdx = typeIdx - 6 |
| 73 | + expect(joined.slice(typeColorIdx, typeColorIdx + 5)).toBe(`\x1b[${expected[type]}m`) |
| 74 | + }) |
| 75 | + } |
| 76 | + }) |
| 77 | +}) |
0 commit comments