-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathBrowserClient.test.ts
More file actions
541 lines (464 loc) · 16.9 KB
/
BrowserClient.test.ts
File metadata and controls
541 lines (464 loc) · 16.9 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import {
AutoEnvAttributes,
LDLogger,
LDSingleKindContext,
} from '@launchdarkly/js-client-sdk-common';
import { makeClient } from '../src/BrowserClient';
import { makeBasicPlatform } from './BrowserClient.mocks';
import { goodBootstrapDataWithReasons } from './testBootstrapData';
describe('given a mock platform for a BrowserClient', () => {
const logger: LDLogger = {
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
let platform: any;
beforeEach(() => {
Object.defineProperty(window, 'location', {
value: { href: 'http://browserclientintegration.com' },
writable: true,
});
jest.useFakeTimers().setSystemTime(new Date('2024-09-19'));
platform = makeBasicPlatform();
});
it('includes urls in custom events', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
},
platform,
);
await client.identify({ key: 'user-key', kind: 'user' });
await client.flush();
client.track('user-key', undefined, 1);
await client.flush();
expect(JSON.parse(platform.requests.fetch.mock.calls[3][1].body)[0]).toMatchObject({
kind: 'custom',
creationDate: 1726704000000,
key: 'user-key',
context: {
key: 'user-key',
kind: 'user',
},
metricValue: 1,
url: 'http://browserclientintegration.com',
});
});
it('can filter URLs in custom events', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
eventUrlTransformer: (url: string) =>
url.replace('http://browserclientintegration.com', 'http://filtered.org'),
},
platform,
);
await client.identify({ key: 'user-key', kind: 'user' });
await client.flush();
client.track('user-key', undefined, 1);
await client.flush();
const events = JSON.parse(platform.requests.fetch.mock.calls[3][1].body);
const customEvent = events.find((e: any) => e.kind === 'custom');
expect(customEvent).toMatchObject({
kind: 'custom',
creationDate: 1726704000000,
key: 'user-key',
context: {
key: 'user-key',
kind: 'user',
},
metricValue: 1,
url: 'http://filtered.org',
});
});
it('can filter URLs in click events', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
eventUrlTransformer: (url: string) =>
url.replace('http://browserclientintegration.com', 'http://filtered.org'),
},
platform,
);
await client.identify({ key: 'user-key', kind: 'user' });
await client.flush();
// Simulate a click event
const button = document.createElement('button');
button.className = 'button';
document.body.appendChild(button);
button.click();
while (platform.requests.fetch.mock.calls.length < 4) {
// eslint-disable-next-line no-await-in-loop
await client.flush();
jest.runAllTicks();
}
const events = JSON.parse(platform.requests.fetch.mock.calls[3][1].body);
const clickEvent = events.find((e: any) => e.kind === 'click');
expect(clickEvent).toMatchObject({
kind: 'click',
creationDate: 1726704000000,
key: 'click',
contextKeys: {
user: 'user-key',
},
url: 'http://filtered.org',
});
document.body.removeChild(button);
});
it('can filter URLs in pageview events', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
eventUrlTransformer: (url: string) =>
url.replace('http://browserclientintegration.com', 'http://filtered.com'),
},
platform,
);
await client.identify({ key: 'user-key', kind: 'user' });
await client.flush();
const events = JSON.parse(platform.requests.fetch.mock.calls[2][1].body);
const pageviewEvent = events.find((e: any) => e.kind === 'pageview');
expect(pageviewEvent).toMatchObject({
kind: 'pageview',
creationDate: 1726704000000,
key: 'pageview',
contextKeys: {
user: 'user-key',
},
url: 'http://filtered.com',
});
});
it('can use bootstrap data', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
},
platform,
);
await client.identify(
{ kind: 'user', key: 'bob' },
{
bootstrap: goodBootstrapDataWithReasons,
},
);
expect(client.jsonVariationDetail('json', undefined)).toEqual({
reason: {
kind: 'OFF',
},
value: ['a', 'b', 'c', 'd'],
variationIndex: 1,
});
});
it('can evaluate flags with bootstrap data before identify completes', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
},
platform,
);
const identifyPromise = client.identify(
{ kind: 'user', key: 'bob' },
{
bootstrap: goodBootstrapDataWithReasons,
},
);
const flagValue = client.jsonVariationDetail('json', undefined);
expect(flagValue).toEqual({
reason: {
kind: 'OFF',
},
value: ['a', 'b', 'c', 'd'],
variationIndex: 1,
});
expect(client.getContext()).toBeUndefined();
// Wait for identify to complete
await identifyPromise;
// Verify that active context is now set
expect(client.getContext()).toEqual({ kind: 'user', key: 'bob' });
});
it('can shed intermediate identify calls', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
platform,
);
const promise1 = client.identify({ key: 'user-key-1', kind: 'user' });
const promise2 = client.identify({ key: 'user-key-2', kind: 'user' });
const promise3 = client.identify({ key: 'user-key-3', kind: 'user' });
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
expect(result1).toEqual({ status: 'completed' });
expect(result2).toEqual({ status: 'shed' });
expect(result3).toEqual({ status: 'completed' });
// With events and goals disabled the only fetch calls should be for polling requests.
expect(platform.requests.fetch.mock.calls.length).toBe(2);
});
it('calls beforeIdentify in order', async () => {
const order: string[] = [];
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
sendEvents: false,
fetchGoals: false,
hooks: [
{
beforeIdentify: (hookContext, data) => {
if ('kind' in hookContext.context && hookContext.context.kind !== 'multi') {
order.push((hookContext.context as LDSingleKindContext).key);
}
return data;
},
getMetadata: () => ({
name: 'test-hook',
version: '1.0.0',
}),
},
],
},
platform,
);
const promise1 = client.identify({ key: 'user-key-1', kind: 'user' });
const promise2 = client.identify({ key: 'user-key-2', kind: 'user' });
const promise3 = client.identify({ key: 'user-key-3', kind: 'user' });
await Promise.all([promise1, promise2, promise3]);
expect(order).toEqual(['user-key-1', 'user-key-2', 'user-key-3']);
});
it('completes identify calls in order', async () => {
const order: string[] = [];
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
sendEvents: false,
fetchGoals: false,
hooks: [
{
afterIdentify: (hookContext, data, result) => {
if (result.status === 'shed') {
return data;
}
if ('kind' in hookContext.context && hookContext.context.kind !== 'multi') {
order.push((hookContext.context as LDSingleKindContext).key);
}
return data;
},
getMetadata: () => ({
name: 'test-hook',
version: '1.0.0',
}),
},
],
},
platform,
);
const promise1 = client.identify({ key: 'user-key-1', kind: 'user' });
const promise2 = client.identify({ key: 'user-key-2', kind: 'user' });
const promise3 = client.identify({ key: 'user-key-3', kind: 'user' });
await Promise.all([promise1, promise2, promise3]);
// user-key-2 is shed, so it is not included in the order
expect(order).toEqual(['user-key-1', 'user-key-3']);
});
it('completes awaited identify calls in order without shedding', async () => {
const order: string[] = [];
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{
streaming: false,
logger,
diagnosticOptOut: true,
sendEvents: false,
fetchGoals: false,
hooks: [
{
afterIdentify: (hookContext, data, result) => {
if (result.status === 'shed') {
return data;
}
if ('kind' in hookContext.context && hookContext.context.kind !== 'multi') {
order.push((hookContext.context as LDSingleKindContext).key);
}
return data;
},
getMetadata: () => ({
name: 'test-hook',
version: '1.0.0',
}),
},
],
},
platform,
);
const result1 = await client.identify({ key: 'user-key-1', kind: 'user' });
const result2 = await client.identify({ key: 'user-key-2', kind: 'user' });
const result3 = await client.identify({ key: 'user-key-3', kind: 'user' });
expect(result1.status).toEqual('completed');
expect(result2.status).toEqual('completed');
expect(result3.status).toEqual('completed');
// user-key-2 is shed, so it is not included in the order
expect(order).toEqual(['user-key-1', 'user-key-2', 'user-key-3']);
});
it('can shed intermediate identify calls without waiting for results', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
platform,
);
const promise1 = client.identify({ key: 'user-key-1', kind: 'user' });
const promise2 = client.identify({ key: 'user-key-2', kind: 'user' });
const promise3 = client.identify({ key: 'user-key-3', kind: 'user' });
await Promise.all([promise1, promise2, promise3]);
// With events and goals disabled the only fetch calls should be for polling requests.
expect(platform.requests.fetch.mock.calls.length).toBe(2);
});
it('it does not shed non-shedable identify calls', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
platform,
);
const promise1 = client.identify({ key: 'user-key-1', kind: 'user' }, { sheddable: false });
const promise2 = client.identify({ key: 'user-key-2', kind: 'user' }, { sheddable: false });
const promise3 = client.identify({ key: 'user-key-3', kind: 'user' }, { sheddable: false });
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
expect(result1).toEqual({ status: 'completed' });
expect(result2).toEqual({ status: 'completed' });
expect(result3).toEqual({ status: 'completed' });
// With events and goals disabled the only fetch calls should be for polling requests.
expect(platform.requests.fetch.mock.calls.length).toBe(3);
});
it('blocks until the client is ready when waitForInitialization is called', async () => {
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
platform,
);
const waitPromise = client.waitForInitialization({ timeout: 10 });
const identifyPromise = client.identify({ key: 'user-key', kind: 'user' });
await Promise.all([waitPromise, identifyPromise]);
await expect(waitPromise).resolves.toEqual({ status: 'complete' });
await expect(identifyPromise).resolves.toEqual({ status: 'completed' });
});
it('resolves waitForInitialization with timeout status when initialization does not complete before the timeout', async () => {
jest.useRealTimers();
// Create a platform with a delayed fetch response
const delayedPlatform = makeBasicPlatform();
let resolveFetch: (value: any) => void;
const delayedFetchPromise = new Promise((resolve) => {
resolveFetch = resolve;
});
// Mock fetch to return a promise that won't resolve until we explicitly resolve it
delayedPlatform.requests.fetch = jest.fn((_url: string, _options: any) =>
delayedFetchPromise.then(() => ({})),
) as any;
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
delayedPlatform,
);
// Start identify which will trigger a fetch that won't complete
client.identify({ key: 'user-key', kind: 'user' });
// Call waitForInitialization with a short timeout (0.1 seconds)
const waitPromise = client.waitForInitialization({ timeout: 0.1 });
// Verify that waitForInitialization rejects with a timeout error
await expect(waitPromise).resolves.toEqual({ status: 'timeout' });
// Clean up: resolve the fetch to avoid hanging promises and restore fake timers
resolveFetch!({});
jest.useFakeTimers();
});
it('resolves waitForInitialization with failed status immediately when identify fails', async () => {
const errorPlatform = makeBasicPlatform();
const identifyError = new Error('Network error');
// Mock fetch to reject with an error
errorPlatform.requests.fetch = jest.fn((_url: string, _options: any) =>
Promise.reject(identifyError),
) as any;
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
errorPlatform,
);
// Call waitForInitialization first - this creates the promise
const waitPromise = client.waitForInitialization({ timeout: 10 });
// Start identify which will fail
const identifyPromise = client.identify({ key: 'user-key', kind: 'user' });
await jest.advanceTimersByTimeAsync(4000); // trigger all poll retries
// Wait for identify to fail
await expect(identifyPromise).resolves.toEqual({
status: 'error',
error: identifyError,
});
// Verify that waitForInitialization returns immediately with failed status
await expect(waitPromise).resolves.toEqual({
status: 'failed',
error: identifyError,
});
});
it('resolves waitForInitialization with failed status when identify fails before waitForInitialization is called', async () => {
const errorPlatform = makeBasicPlatform();
const identifyError = new Error('Network error');
// Mock fetch to reject with an error
errorPlatform.requests.fetch = jest.fn((_url: string, _options: any) =>
Promise.reject(identifyError),
) as any;
const client = makeClient(
'client-side-id',
AutoEnvAttributes.Disabled,
{ streaming: false, logger, diagnosticOptOut: true, sendEvents: false, fetchGoals: false },
errorPlatform,
);
// Start identify which will fail BEFORE waitForInitialization is called
const identifyPromise = client.identify({ key: 'user-key', kind: 'user' });
await jest.advanceTimersByTimeAsync(4000); // trigger all poll retries
// Wait for identify to fail
await expect(identifyPromise).resolves.toEqual({
status: 'error',
error: identifyError,
});
// Now call waitForInitialization AFTER identify has already failed
// It should return the failed status immediately, not timeout
const waitPromise = client.waitForInitialization({ timeout: 10 });
// Verify that waitForInitialization returns immediately with failed status
await expect(waitPromise).resolves.toEqual({
status: 'failed',
error: identifyError,
});
});
});