|
| 1 | +import 'expect-more-jest'; |
| 2 | +import stringify from 'fast-safe-stringify'; |
| 3 | +import LogMessage from '../LogMessage'; |
| 4 | +import jsonFormatter from './json'; |
| 5 | + |
| 6 | +const defaultOpts = { |
| 7 | + meta: {}, |
| 8 | + dynamicMeta: null, |
| 9 | + tags: [], |
| 10 | + levelKey: '_logLevel', |
| 11 | + messageKey: 'msg', |
| 12 | + tagsKey: '_tags', |
| 13 | + replacer: null |
| 14 | +}; |
| 15 | + |
| 16 | +const logObject = { |
| 17 | + level: 'info', |
| 18 | + msg: 'info test', |
| 19 | + meta: {}, |
| 20 | + tags: [] |
| 21 | +}; |
| 22 | + |
| 23 | + |
| 24 | +describe('formatters/json', () => { |
| 25 | + it('should export a closure function', () => { |
| 26 | + expect(typeof jsonFormatter).toBe('function'); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should return a formatter function', () => { |
| 30 | + expect(typeof jsonFormatter()).toBe('function'); |
| 31 | + }); |
| 32 | + |
| 33 | + const replacerOpts = { |
| 34 | + ...defaultOpts, |
| 35 | + meta: { ssn: '444-55-6666' }, |
| 36 | + replacer(key: string, value: unknown) { |
| 37 | + if(key === 'ssn') { |
| 38 | + return `${(value as string).substring(0, 3)}-**-****`; |
| 39 | + } |
| 40 | + |
| 41 | + return value; |
| 42 | + } |
| 43 | + }; |
| 44 | + |
| 45 | + const msg = new LogMessage({ ...logObject }, replacerOpts); |
| 46 | + |
| 47 | + const formatter = jsonFormatter(); |
| 48 | + const result = formatter(msg, replacerOpts, stringify); |
| 49 | + |
| 50 | + it('should return log in JSON format', () => { |
| 51 | + expect(result).toBeJsonString(); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should run replacer function', () => { |
| 55 | + expect(JSON.parse(result).ssn).toBe('444-**-****'); |
| 56 | + }); |
| 57 | + |
| 58 | + it('should not run replacer function when not defined', () => { |
| 59 | + const msgNoReplacer = new LogMessage({ ...logObject }, { |
| 60 | + ...defaultOpts, |
| 61 | + meta: { ssn: '444-55-6666' } |
| 62 | + }); |
| 63 | + |
| 64 | + const noReplacerResult = formatter(msgNoReplacer, defaultOpts, stringify); |
| 65 | + |
| 66 | + expect(JSON.parse(noReplacerResult).ssn).toBe('444-55-6666'); |
| 67 | + }); |
| 68 | + |
| 69 | + it('should pretty print JSON when dev is "true"', () => { |
| 70 | + const opts = { |
| 71 | + ...defaultOpts, |
| 72 | + dev: true, |
| 73 | + meta: { ssn: '444-55-6666' } |
| 74 | + }; |
| 75 | + |
| 76 | + const msgDev = new LogMessage({ ...logObject }, opts); |
| 77 | + const prettyResult = formatter(msgDev, opts, stringify); |
| 78 | + |
| 79 | + expect(/\n/g.test(prettyResult)).toBe(true); |
| 80 | + }); |
| 81 | +}); |
0 commit comments