autobaan/tests/unit/common/logger.test.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-01-20 15:37:15 +01:00
import dayjs from '../../../src/common/dayjs'
import { Logger, LogLevel } from '../../../src/common/logger'
2023-01-20 15:37:15 +01:00
jest.useFakeTimers().setSystemTime(new Date('2023-01-01'))
describe('Logger', () => {
2022-11-27 16:09:30 +01:00
beforeEach(() => {
jest.resetAllMocks()
})
test('should log messages', () => {
const consoleLogSpy = jest.fn()
const consoleErrorSpy = jest.fn()
jest.spyOn(console, 'log').mockImplementation(consoleLogSpy)
jest.spyOn(console, 'error').mockImplementation(consoleErrorSpy)
const logger = new Logger('tag', 'abc', LogLevel.DEBUG)
logger.debug('first')
logger.info('second')
logger.error('third', { errorMessage: 'test' })
expect(consoleLogSpy).toHaveBeenCalledTimes(2)
expect(consoleLogSpy).toHaveBeenNthCalledWith(
1,
2023-01-20 15:37:15 +01:00
'(%s) <%s> [%s] %s: %s',
dayjs().format(),
'tag',
'abc',
'DEBUG',
'first'
)
expect(consoleLogSpy).toHaveBeenNthCalledWith(
2,
2023-01-20 15:37:15 +01:00
'(%s) <%s> [%s] %s: %s',
dayjs().format(),
'tag',
'abc',
'INFO',
'second'
)
expect(consoleErrorSpy).toHaveBeenCalledTimes(1)
expect(consoleErrorSpy).toHaveBeenCalledWith(
2023-01-20 15:37:15 +01:00
'(%s) <%s> [%s] %s: %s - %O',
dayjs().format(),
'tag',
'abc',
'ERROR',
'third',
{ errorMessage: 'test' }
)
})
test('should log only when level is >= LogLevel of LoggerInstance', () => {
const consoleLogSpy = jest.fn()
jest.spyOn(console, 'log').mockImplementationOnce(consoleLogSpy)
const logger = new Logger('tag', 'abc', LogLevel.INFO)
logger.debug("shouldn't appear")
expect(consoleLogSpy).not.toHaveBeenCalled()
})
2022-11-27 16:09:30 +01:00
test('should obfuscate password from message', () => {
const consoleLogSpy = jest.fn()
const consoleErrorSpy = jest.fn()
jest.spyOn(console, 'log').mockImplementation(consoleLogSpy)
jest.spyOn(console, 'error').mockImplementation(consoleErrorSpy)
const logger = new Logger('tag', 'abc', LogLevel.DEBUG)
logger.info('first', { password: 'test' })
2022-11-27 16:09:30 +01:00
expect(consoleLogSpy).toHaveBeenCalledTimes(1)
expect(consoleLogSpy).toHaveBeenNthCalledWith(
1,
2023-01-20 15:37:15 +01:00
'(%s) <%s> [%s] %s: %s - %O',
dayjs().format(),
2022-11-27 16:09:30 +01:00
'tag',
'abc',
'INFO',
'first',
{ password: '***' }
2022-11-27 16:09:30 +01:00
)
})
})