morgan-like-format-options.spec.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import type { IncomingMessage, ServerResponse } from 'node:http';
  2. import { describe, expect, it } from 'vitest';
  3. import { morganLikeFormatOptions } from './morgan-like-format-options';
  4. // Strip ANSI escape codes for plain-text assertions (avoids control-char lint rule)
  5. const ANSI_RE = new RegExp(`${String.fromCharCode(27)}\\[\\d+m`, 'g');
  6. const strip = (s: string) => s.replace(ANSI_RE, '');
  7. function fakeReq(method: string, url: string): IncomingMessage {
  8. return { method, url } as IncomingMessage;
  9. }
  10. function fakeRes(statusCode: number): ServerResponse {
  11. return { statusCode } as unknown as ServerResponse;
  12. }
  13. describe('morganLikeFormatOptions', () => {
  14. describe('customSuccessMessage', () => {
  15. it('formats as METHOD /url STATUS - TIMEms', () => {
  16. const msg = morganLikeFormatOptions.customSuccessMessage(
  17. fakeReq('GET', '/page/path'),
  18. fakeRes(200),
  19. 12.4,
  20. );
  21. expect(strip(msg)).toBe('GET /page/path 200 - 12ms');
  22. });
  23. it('rounds responseTime to nearest integer', () => {
  24. const msg = morganLikeFormatOptions.customSuccessMessage(
  25. fakeReq('POST', '/api'),
  26. fakeRes(201),
  27. 0.7,
  28. );
  29. expect(strip(msg)).toBe('POST /api 201 - 1ms');
  30. });
  31. });
  32. describe('customErrorMessage', () => {
  33. it('includes error message', () => {
  34. const msg = morganLikeFormatOptions.customErrorMessage(
  35. fakeReq('PUT', '/data'),
  36. fakeRes(500),
  37. new Error('db timeout'),
  38. );
  39. expect(strip(msg)).toBe('PUT /data 500 - db timeout');
  40. });
  41. });
  42. describe('customLogLevel', () => {
  43. it('returns info for 2xx responses', () => {
  44. const level = morganLikeFormatOptions.customLogLevel(
  45. fakeReq('GET', '/'),
  46. fakeRes(200),
  47. undefined,
  48. );
  49. expect(level).toBe('info');
  50. });
  51. it('returns warn for 4xx responses', () => {
  52. const level = morganLikeFormatOptions.customLogLevel(
  53. fakeReq('GET', '/'),
  54. fakeRes(404),
  55. undefined,
  56. );
  57. expect(level).toBe('warn');
  58. });
  59. it('returns error for 5xx responses', () => {
  60. const level = morganLikeFormatOptions.customLogLevel(
  61. fakeReq('GET', '/'),
  62. fakeRes(503),
  63. undefined,
  64. );
  65. expect(level).toBe('error');
  66. });
  67. it('returns error when error object is present', () => {
  68. const level = morganLikeFormatOptions.customLogLevel(
  69. fakeReq('GET', '/'),
  70. fakeRes(200),
  71. new Error('unexpected'),
  72. );
  73. expect(level).toBe('error');
  74. });
  75. });
  76. });