-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathanalytics.middleware.unit.tests.js
More file actions
241 lines (197 loc) · 6.33 KB
/
Copy pathanalytics.middleware.unit.tests.js
File metadata and controls
241 lines (197 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/**
* Module dependencies.
*/
import { jest, beforeEach, afterEach, describe, test, expect } from '@jest/globals';
/**
* Unit tests for analytics auto-capture middleware
*/
describe('Analytics middleware unit tests:', () => {
let analyticsMiddleware;
let createAnalyticsMiddleware;
let mockTrack;
/** @type {import('express').Request} */
let req;
/** @type {import('express').Response & { _finishHandlers: Function[] }} */
let res;
/** @type {jest.Mock} */
let next;
beforeEach(async () => {
jest.resetModules();
mockTrack = jest.fn();
jest.unstable_mockModule('../../services/analytics.js', () => ({
default: {
track: mockTrack,
},
}));
const mod = await import('../analytics.js');
analyticsMiddleware = mod.default;
createAnalyticsMiddleware = mod.createAnalyticsMiddleware;
// Build minimal Express-like req/res mocks
req = {
originalUrl: '/api/tasks',
url: '/api/tasks',
method: 'GET',
user: { _id: 'user-123' },
organization: { _id: 'org-456' },
};
const finishHandlers = [];
res = {
statusCode: 200,
on: jest.fn((event, handler) => {
if (event === 'finish') finishHandlers.push(handler);
}),
_finishHandlers: finishHandlers,
};
next = jest.fn();
});
afterEach(() => {
jest.restoreAllMocks();
});
/**
* Helper — trigger all registered 'finish' handlers on res.
*/
const triggerFinish = () => {
res._finishHandlers.forEach((fn) => fn());
};
test('should call next immediately', () => {
analyticsMiddleware(req, res, next);
expect(next).toHaveBeenCalledTimes(1);
});
test('should register a finish listener on res', () => {
analyticsMiddleware(req, res, next);
expect(res.on).toHaveBeenCalledWith('finish', expect.any(Function));
});
test('should track api_request with correct properties on finish', () => {
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
'user-123',
'api_request',
expect.objectContaining({
endpoint: '/api/tasks',
method: 'GET',
statusCode: 200,
responseTime: expect.any(Number),
}),
{ company: 'org-456' },
);
});
test('should use "anonymous" when req.user is absent', () => {
req.user = undefined;
req.organization = undefined;
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
'anonymous',
'api_request',
expect.any(Object),
undefined,
);
});
test('should use "anonymous" when req.user._id is missing', () => {
req.user = {};
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
'anonymous',
'api_request',
expect.any(Object),
{ company: 'org-456' },
);
});
test('should omit groups when req.organization is absent', () => {
req.organization = undefined;
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
'user-123',
'api_request',
expect.any(Object),
undefined,
);
});
test('should skip /api/health routes', () => {
req.originalUrl = '/api/health';
analyticsMiddleware(req, res, next);
expect(next).toHaveBeenCalledTimes(1);
expect(res.on).not.toHaveBeenCalled();
});
test('should skip /api/health sub-routes', () => {
req.originalUrl = '/api/health/ready';
analyticsMiddleware(req, res, next);
expect(res.on).not.toHaveBeenCalled();
});
test('should skip /public static assets', () => {
req.originalUrl = '/public/images/logo.png';
analyticsMiddleware(req, res, next);
expect(res.on).not.toHaveBeenCalled();
});
test('should skip /favicon requests', () => {
req.originalUrl = '/favicon.ico';
analyticsMiddleware(req, res, next);
expect(res.on).not.toHaveBeenCalled();
});
test('should capture correct statusCode from res on finish', () => {
analyticsMiddleware(req, res, next);
res.statusCode = 404;
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
expect.any(String),
'api_request',
expect.objectContaining({ statusCode: 404 }),
expect.anything(),
);
});
test('should capture responseTime as a non-negative number', () => {
analyticsMiddleware(req, res, next);
triggerFinish();
const properties = mockTrack.mock.calls[0][2];
expect(properties.responseTime).toBeGreaterThanOrEqual(0);
});
test('should fall back to req.url when originalUrl is absent', () => {
req.originalUrl = undefined;
req.url = '/api/fallback';
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
expect.any(String),
'api_request',
expect.objectContaining({ endpoint: '/api/fallback' }),
expect.anything(),
);
});
test('should strip query strings from endpoint', () => {
req.originalUrl = '/api/tasks?page=1&secret=abc';
analyticsMiddleware(req, res, next);
triggerFinish();
expect(mockTrack).toHaveBeenCalledWith(
expect.any(String),
'api_request',
expect.objectContaining({ endpoint: '/api/tasks' }),
expect.anything(),
);
});
test('should accept custom skipPrefixes via createAnalyticsMiddleware', () => {
const customMiddleware = createAnalyticsMiddleware({ skipPrefixes: ['/custom'] });
req.originalUrl = '/custom/path';
customMiddleware(req, res, next);
expect(next).toHaveBeenCalledTimes(1);
expect(res.on).not.toHaveBeenCalled();
});
test('should not skip default prefixes when custom skipPrefixes provided', () => {
const customMiddleware = createAnalyticsMiddleware({ skipPrefixes: ['/custom'] });
req.originalUrl = '/api/health';
customMiddleware(req, res, next);
// /api/health is NOT in the custom prefixes, so it should be tracked
expect(res.on).toHaveBeenCalledWith('finish', expect.any(Function));
});
test('should not throw when track throws inside finish handler', () => {
mockTrack.mockImplementation(() => {
throw new Error('PostHog exploded');
});
analyticsMiddleware(req, res, next);
// The finish handler should swallow the error
expect(() => triggerFinish()).not.toThrow();
expect(mockTrack).toHaveBeenCalledTimes(1);
});
});