|
| 1 | +import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest'; |
| 2 | +import { createBrowserLogger } from '../src'; |
| 3 | + |
| 4 | +describe('createBrowserLogger', () => { |
| 5 | + let consoleLogSpy: ReturnType<typeof vi.spyOn>; |
| 6 | + let consoleWarnSpy: ReturnType<typeof vi.spyOn>; |
| 7 | + let consoleErrorSpy: ReturnType<typeof vi.spyOn>; |
| 8 | + |
| 9 | + beforeEach(() => { |
| 10 | + consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 11 | + consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 12 | + consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 13 | + }); |
| 14 | + |
| 15 | + afterEach(() => { |
| 16 | + vi.restoreAllMocks(); |
| 17 | + }); |
| 18 | + |
| 19 | + it('should log message with default type', () => { |
| 20 | + const logger = createBrowserLogger('1.0.0'); |
| 21 | + |
| 22 | + logger('Test message'); |
| 23 | + |
| 24 | + expect(consoleLogSpy).toHaveBeenCalledWith( |
| 25 | + '%cHawk (1.0.0)%c Test message', |
| 26 | + expect.stringContaining('background-color'), |
| 27 | + 'color: inherit' |
| 28 | + ); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should log message with specified type', () => { |
| 32 | + const logger = createBrowserLogger('2.0.0'); |
| 33 | + |
| 34 | + logger('Warning message', 'warn'); |
| 35 | + |
| 36 | + expect(consoleWarnSpy).toHaveBeenCalledWith( |
| 37 | + '%cHawk (2.0.0)%c Warning message', |
| 38 | + expect.stringContaining('background-color'), |
| 39 | + 'color: inherit' |
| 40 | + ); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should log error with args', () => { |
| 44 | + const logger = createBrowserLogger('3.0.0'); |
| 45 | + const errorObj = new Error('Test error'); |
| 46 | + |
| 47 | + logger('Error occurred', 'error', errorObj); |
| 48 | + |
| 49 | + expect(consoleErrorSpy).toHaveBeenCalledWith( |
| 50 | + '%cHawk (3.0.0)%c Error occurred %o', |
| 51 | + expect.stringContaining('background-color'), |
| 52 | + 'color: inherit', |
| 53 | + errorObj |
| 54 | + ); |
| 55 | + }); |
| 56 | + |
| 57 | + it('should handle time/timeEnd types', () => { |
| 58 | + const consoleTimeSpy = vi.spyOn(console, 'time').mockImplementation(() => {}); |
| 59 | + const logger = createBrowserLogger('4.0.0'); |
| 60 | + |
| 61 | + logger('Timer started', 'time'); |
| 62 | + |
| 63 | + expect(consoleTimeSpy).toHaveBeenCalledWith( |
| 64 | + expect.stringContaining('Hawk (4.0.0)') |
| 65 | + ); |
| 66 | + |
| 67 | + consoleTimeSpy.mockRestore(); |
| 68 | + }); |
| 69 | + |
| 70 | + it('should not throw when console method is unavailable', () => { |
| 71 | + const logger = createBrowserLogger('5.0.0'); |
| 72 | + |
| 73 | + expect(() => { |
| 74 | + // @ts-expect-error - testing invalid type |
| 75 | + logger('Test', 'invalidType'); |
| 76 | + }).not.toThrow(); |
| 77 | + }); |
| 78 | +}); |
0 commit comments