-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathposthog-node.spec.ts
More file actions
2835 lines (2465 loc) · 87.9 KB
/
posthog-node.spec.ts
File metadata and controls
2835 lines (2465 loc) · 87.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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { PostHog, PostHogOptions } from '@/entrypoints/index.node'
import { anyFlagsCall, anyLocalEvalCall, apiImplementation, isPending, wait, waitForPromises } from './utils'
import { randomUUID } from 'crypto'
jest.mock('../version', () => ({ version: '1.2.3' }))
const mockedFetch = jest.spyOn(globalThis, 'fetch').mockImplementation()
const posthogImmediateResolveOptions: PostHogOptions = {
fetchRetryCount: 0,
}
const waitForFlushTimer = async (): Promise<void> => {
await waitForPromises()
// To trigger the flush via the timer
jest.runOnlyPendingTimers()
// Then wait for the flush promise
await waitForPromises()
}
const getLastBatchEvents = (): any[] | undefined => {
expect(mockedFetch).toHaveBeenCalledWith('http://example.com/batch/', expect.objectContaining({ method: 'POST' }))
// reverse mock calls array to get the last call
const call = mockedFetch.mock.calls.reverse().find((x) => (x[0] as string).includes('/batch/'))
if (!call) {
return undefined
}
return JSON.parse((call[1] as any).body as any).batch
}
jest.retryTimes(3)
describe('PostHog Node.js', () => {
let posthog: PostHog
let warnSpy: jest.SpyInstance
let logSpy: jest.SpyInstance
let infoSpy: jest.SpyInstance
let errorSpy: jest.SpyInstance
jest.useFakeTimers()
beforeEach(() => {
warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
logSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
infoSpy = jest.spyOn(console, 'info').mockImplementation(() => {})
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
})
mockedFetch.mockResolvedValue({
status: 200,
text: () => Promise.resolve('ok'),
json: () =>
Promise.resolve({
status: 'ok',
}),
} as any)
})
afterEach(async () => {
mockedFetch.mockResolvedValue({
status: 200,
text: () => Promise.resolve('ok'),
json: () =>
Promise.resolve({
status: 'ok',
}),
} as any)
// ensure clean shutdown & no test interdependencies
await posthog.shutdown()
warnSpy.mockRestore()
logSpy.mockRestore()
errorSpy.mockRestore()
})
describe('core methods', () => {
it('should capture an event to shared queue', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' }, groups: { org: 123 } })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toEqual([
{
distinct_id: '123',
event: 'test-event',
properties: {
$groups: { org: 123 },
foo: 'bar',
$geoip_disable: true,
$lib: 'posthog-node',
$lib_version: '1.2.3',
},
uuid: expect.any(String),
timestamp: expect.any(String),
type: 'capture',
library: 'posthog-node',
library_version: '1.2.3',
},
])
})
it('shouldnt muddy subsequent capture calls', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' }, groups: { org: 123 } })
await waitForFlushTimer()
expect(getLastBatchEvents()?.[0]).toEqual(
expect.objectContaining({
distinct_id: '123',
event: 'test-event',
properties: expect.objectContaining({
$groups: { org: 123 },
foo: 'bar',
}),
library: 'posthog-node',
library_version: '1.2.3',
})
)
mockedFetch.mockClear()
posthog.capture({
distinctId: '123',
event: 'test-event',
properties: { foo: 'bar' },
groups: { other_group: 'x' },
})
await waitForFlushTimer()
expect(getLastBatchEvents()?.[0]).toEqual(
expect.objectContaining({
distinct_id: '123',
event: 'test-event',
properties: expect.objectContaining({
$groups: { other_group: 'x' },
foo: 'bar',
$geoip_disable: true,
}),
library: 'posthog-node',
library_version: '1.2.3',
})
)
})
it('should capture identify events on shared queue', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.identify({ distinctId: '123', properties: { foo: 'bar' } })
jest.runOnlyPendingTimers()
await waitForPromises()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
event: '$identify',
properties: {
$set: {
foo: 'bar',
},
$geoip_disable: true,
},
},
])
})
it('should handle identify using $set and $set_once', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.identify({ distinctId: '123', properties: { $set: { foo: 'bar' }, $set_once: { vip: true } } })
jest.runOnlyPendingTimers()
await waitForPromises()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
event: '$identify',
properties: {
$set: {
foo: 'bar',
},
$set_once: {
vip: true,
},
$geoip_disable: true,
},
},
])
})
it('should handle identify using $set_once', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.identify({ distinctId: '123', properties: { foo: 'bar', $set_once: { vip: true } } })
jest.runOnlyPendingTimers()
await waitForPromises()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
event: '$identify',
properties: {
$set: {
foo: 'bar',
},
$set_once: {
vip: true,
},
$geoip_disable: true,
},
},
])
})
it('should capture alias events on shared queue', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.alias({ distinctId: '123', alias: '1234' })
jest.runOnlyPendingTimers()
await waitForPromises()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
event: '$create_alias',
properties: {
distinct_id: '123',
alias: '1234',
$geoip_disable: true,
},
},
])
})
it('should allow overriding timestamp', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.capture({ event: 'custom-time', distinctId: '123', timestamp: new Date('2021-02-03') })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
timestamp: '2021-02-03T00:00:00.000Z',
event: 'custom-time',
uuid: expect.any(String),
},
])
})
it('should allow overriding uuid', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
const uuid = randomUUID()
posthog.capture({ event: 'custom-time', distinctId: '123', uuid })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
timestamp: expect.any(String),
event: 'custom-time',
uuid: uuid,
},
])
})
it('should respect disableGeoip setting if passed in', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog.capture({
distinctId: '123',
event: 'test-event',
properties: { foo: 'bar' },
groups: { org: 123 },
disableGeoip: false,
})
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents?.[0].properties).toEqual({
$groups: { org: 123 },
foo: 'bar',
$lib: 'posthog-node',
$lib_version: '1.2.3',
})
})
it('should use default is set, and override on specific disableGeoip calls', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
const client = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
disableGeoip: false,
disableCompression: true,
})
client.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' }, groups: { org: 123 } })
await waitForFlushTimer()
let batchEvents = getLastBatchEvents()
expect(batchEvents?.[0].properties).toEqual({
$groups: { org: 123 },
foo: 'bar',
$lib: 'posthog-node',
$lib_version: '1.2.3',
})
client.capture({
distinctId: '123',
event: 'test-event',
properties: { foo: 'bar' },
groups: { org: 123 },
disableGeoip: true,
})
await waitForFlushTimer()
batchEvents = getLastBatchEvents()
expect(batchEvents?.[0].properties).toEqual({
$groups: { org: 123 },
foo: 'bar',
$lib: 'posthog-node',
$lib_version: '1.2.3',
$geoip_disable: true,
})
client.capture({
distinctId: '123',
event: 'test-event',
properties: { foo: 'bar' },
groups: { org: 123 },
disableGeoip: false,
})
await waitForFlushTimer()
await waitForPromises()
batchEvents = getLastBatchEvents()
expect(batchEvents?.[0].properties).toEqual({
$groups: { org: 123 },
foo: 'bar',
$lib: 'posthog-node',
$lib_version: '1.2.3',
})
await client.shutdown()
})
it('should include registered properties in captured events', async () => {
posthog.register({ registered_prop: 'registered_value', another: 123 })
posthog.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toEqual([
expect.objectContaining({
distinct_id: '123',
event: 'test-event',
properties: expect.objectContaining({
registered_prop: 'registered_value',
another: 123,
foo: 'bar',
}),
}),
])
})
it('should allow capture properties to override registered properties', async () => {
posthog.register({ foo: 'registered_value', only_registered: 'yes' })
posthog.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'override_value' } })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
// The registered-only property should still be present
expect(batchEvents?.[0].properties).toEqual(
expect.objectContaining({
only_registered: 'yes',
foo: 'override_value',
})
)
})
it('should stop including unregistered properties', async () => {
posthog.register({ foo: 'bar', remove_me: 'value' })
posthog.unregister('remove_me')
posthog.capture({ distinctId: '123', event: 'test-event' })
await waitForFlushTimer()
const batchEvents = getLastBatchEvents()
expect(batchEvents?.[0].properties).toEqual(
expect.objectContaining({
foo: 'bar',
})
)
expect(batchEvents?.[0].properties).not.toHaveProperty('remove_me')
})
it('should warn if capture is called with a string', () => {
posthog.debug(true)
// @ts-expect-error - Testing the warning when passing a string instead of an object
posthog.capture('test-event')
expect(warnSpy).toHaveBeenCalledWith(
'[PostHog]',
'Called capture() with a string as the first argument when an object was expected.'
)
warnSpy.mockRestore()
})
it.each([
['capture', { strictCapture: true }],
['capture', { defaults: '2026-03-19' }],
['capture', { defaults: '2026-03-19', strictCapture: undefined }],
['captureImmediate', { strictCapture: true }],
['captureImmediate', { defaults: '2026-03-19' }],
['captureImmediate', { defaults: '2026-03-19', strictCapture: undefined }],
] as const)('should throw if %s is called with a string when %j', async (method, extraOptions) => {
const ph = new PostHog('TEST_API_KEY', { host: 'http://example.com', ...extraOptions })
// @ts-expect-error - Testing the error when passing a string instead of an object
await expect(Promise.resolve().then(() => ph[method]('test-event'))).rejects.toThrow(TypeError)
await ph.shutdown()
})
it.each([
['capture', { defaults: 'unset' as const }],
['captureImmediate', { defaults: 'unset' as const }],
['capture', { defaults: '2026-03-19' as const, strictCapture: false }],
['captureImmediate', { defaults: '2026-03-19' as const, strictCapture: false }],
])('should warn if %s is called with a string when %j', async (method, extraOptions) => {
const ph = new PostHog('TEST_API_KEY', { host: 'http://example.com', ...extraOptions })
ph.debug(true)
// @ts-expect-error - Testing the warning when passing a string instead of an object
ph[method]('test-event')
expect(warnSpy).toHaveBeenCalledWith(
'[PostHog]',
`Called ${method}() with a string as the first argument when an object was expected.`
)
await ph.shutdown()
})
})
describe('before_send', () => {
it('should allow events through when before_send returns the event', async () => {
const beforeSendFn = jest.fn((event) => event)
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: beforeSendFn,
})
ph.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
await waitForFlushTimer()
expect(beforeSendFn).toHaveBeenCalledTimes(1)
expect(beforeSendFn).toHaveBeenCalledWith({
distinctId: '123',
event: 'test-event',
properties: { foo: 'bar' },
groups: undefined,
sendFeatureFlags: undefined,
timestamp: undefined,
disableGeoip: undefined,
uuid: undefined,
})
const batchEvents = getLastBatchEvents()
expect(batchEvents).toHaveLength(1)
expect(batchEvents![0]).toMatchObject({
distinct_id: '123',
event: 'test-event',
properties: expect.objectContaining({ foo: 'bar' }),
})
})
it('should drop events when before_send returns null', async () => {
const beforeSendFn = jest.fn(() => null)
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: beforeSendFn,
})
ph.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
await waitForFlushTimer()
expect(beforeSendFn).toHaveBeenCalledTimes(1)
expect(mockedFetch).not.toHaveBeenCalledWith('http://example.com/batch/', expect.anything())
})
it('should support array of before_send functions', async () => {
const beforeSend1 = jest.fn((event) => ({ ...event, properties: { ...event.properties, added1: true } }))
const beforeSend2 = jest.fn((event) => ({ ...event, properties: { ...event.properties, added2: true } }))
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: [beforeSend1, beforeSend2],
})
ph.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
await waitForFlushTimer()
expect(beforeSend1).toHaveBeenCalledTimes(1)
expect(beforeSend2).toHaveBeenCalledTimes(1)
const batchEvents = getLastBatchEvents()
expect(batchEvents).toHaveLength(1)
expect(batchEvents![0]).toMatchObject({
distinct_id: '123',
event: 'test-event',
properties: expect.objectContaining({ foo: 'bar', added1: true, added2: true }),
})
})
it('should stop processing if any before_send returns null', async () => {
const beforeSend1 = jest.fn((event) => event)
const beforeSend2 = jest.fn(() => null)
const beforeSend3 = jest.fn((event) => event)
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: [beforeSend1, beforeSend2, beforeSend3],
})
ph.capture({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
await waitForFlushTimer()
expect(beforeSend1).toHaveBeenCalledTimes(1)
expect(beforeSend2).toHaveBeenCalledTimes(1)
expect(beforeSend3).not.toHaveBeenCalled()
expect(mockedFetch).not.toHaveBeenCalledWith('http://example.com/batch/', expect.anything())
})
it('should work with captureImmediate', async () => {
const beforeSendFn = jest.fn((event) => ({ ...event, event: 'modified-event' }))
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: beforeSendFn,
})
await ph.captureImmediate({ distinctId: '123', event: 'test-event', properties: { foo: 'bar' } })
expect(beforeSendFn).toHaveBeenCalledTimes(1)
const batchEvents = getLastBatchEvents()
expect(batchEvents).toHaveLength(1)
expect(batchEvents![0]).toMatchObject({
distinct_id: '123',
event: 'modified-event',
properties: expect.objectContaining({ foo: 'bar' }),
})
})
it('should log when event is dropped in debug mode', async () => {
const beforeSendFn = jest.fn(() => null)
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
before_send: beforeSendFn,
})
ph.debug(true)
ph.capture({ distinctId: '123', event: 'test-event' })
await waitForFlushTimer()
expect(logSpy).toHaveBeenCalledWith('[PostHog]', "Event 'test-event' was rejected in beforeSend function")
logSpy.mockRestore()
})
})
describe('shutdown', () => {
beforeEach(() => {
mockedFetch.mockImplementation(async () => {
// simulate network delay
await wait(500)
return Promise.resolve({
status: 200,
text: () => Promise.resolve('ok'),
json: () =>
Promise.resolve({
status: 'ok',
}),
} as any)
})
jest.useRealTimers()
})
afterEach(() => {
jest.useFakeTimers()
})
it('should shutdown cleanly', async () => {
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
flushAt: 1,
disableCompression: true,
})
ph.debug(true)
ph.capture({ event: 'test-event-1', distinctId: '123' })
// start flushing, but don't wait for promise to resolve before resuming events
const flushPromise = ph.flush()
expect(isPending(flushPromise)).toEqual(true)
ph.capture({ event: 'test-event-2', distinctId: '123' })
// start shutdown, but don't wait for promise to resolve before resuming events
const shutdownPromise = ph.shutdown()
ph.capture({ event: 'test-event-3', distinctId: '123' })
// wait for shutdown to finish
await shutdownPromise
expect(isPending(flushPromise)).toEqual(false)
expect(3).toEqual(logSpy.mock.calls.filter((call) => call[1].includes('capture')).length)
const flushedEvents = logSpy.mock.calls.filter((call) => call[1].includes('flush')).flatMap((flush) => flush[2])
expect(flushedEvents).toMatchObject([
{ event: 'test-event-1' },
{ event: 'test-event-2' },
{ event: 'test-event-3' },
])
})
it('should shutdown cleanly with pending capture flag promises', async () => {
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
flushAt: 4,
disableCompression: true,
})
ph.debug(true)
for (let i = 0; i < 10; i++) {
ph.capture({ event: 'test-event', distinctId: `${i}`, sendFeatureFlags: true })
}
await ph.shutdown()
// all capture calls happen during shutdown
const batchEvents = getLastBatchEvents()
expect(batchEvents?.length).toEqual(6)
expect(batchEvents?.[batchEvents?.length - 1]).toMatchObject({
// last event in batch
distinct_id: '9',
event: 'test-event',
library: 'posthog-node',
library_version: '1.2.3',
properties: {
$lib: 'posthog-node',
$lib_version: '1.2.3',
$geoip_disable: true,
},
timestamp: expect.any(String),
type: 'capture',
})
expect(10).toEqual(logSpy.mock.calls.filter((call) => call[1].includes('capture')).length)
// 1 for the captured events, 1 for the final flush of feature flag called events
expect(2).toEqual(logSpy.mock.calls.filter((call) => call[1].includes('flush')).length)
})
})
describe('request timeout', () => {
beforeEach(() => {
jest.useRealTimers()
})
afterEach(() => {
jest.useFakeTimers()
})
it('should abort a slow fetch after requestTimeout', async () => {
// A fetch that hangs forever but respects the AbortSignal — just like a real
// server that never responds. When our AbortController fires, the signal's
// abort event rejects the promise, mimicking real fetch abort behavior.
const hangingFetch = jest.fn((_url: string, init?: { signal?: AbortSignal }) => {
return new Promise<Response>((_resolve, reject) => {
if (init?.signal?.aborted) {
reject(new DOMException('The operation was aborted', 'AbortError'))
return
}
init?.signal?.addEventListener('abort', () => {
reject(new DOMException('The operation was aborted', 'AbortError'))
})
})
})
const ph = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetch: hangingFetch as any,
fetchRetryCount: 0,
flushAt: 100, // high value so capture() doesn't auto-flush
flushInterval: 0,
requestTimeout: 10,
disableCompression: true,
})
const errors: any[] = []
ph.on('error', (err: any) => errors.push(err))
ph.capture({ event: 'test-event', distinctId: '123' })
// shutdown() joins the promise queue (waits for capture's async prepareEventMessage),
// then flushes. The flush calls fetchWithRetry → hangingFetch → abort fires after 10ms.
// _flush() catch emits 'error' (posthog-core-stateless.ts:1159) and re-throws.
// doShutdown() catches the PostHogFetchError and returns cleanly.
await ph.shutdown()
expect(hangingFetch).toHaveBeenCalled()
expect(errors).toHaveLength(1)
expect(errors[0].name).toBe('PostHogFetchNetworkError')
expect(errors[0].error.name).toBe('AbortError')
}, 10000)
})
describe('groupIdentify', () => {
it('should identify group with unique id', async () => {
posthog.groupIdentify({ groupType: 'posthog', groupKey: 'team-1', properties: { analytics: true } })
jest.runOnlyPendingTimers()
await posthog.flush()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '$posthog_team-1',
event: '$groupidentify',
properties: {
$group_type: 'posthog',
$group_key: 'team-1',
$group_set: { analytics: true },
$lib: 'posthog-node',
$geoip_disable: true,
},
},
])
})
it('should allow passing optional distinctID to identify group', async () => {
posthog.groupIdentify({
groupType: 'posthog',
groupKey: 'team-1',
properties: { analytics: true },
distinctId: '123',
})
jest.runOnlyPendingTimers()
await posthog.flush()
const batchEvents = getLastBatchEvents()
expect(batchEvents).toMatchObject([
{
distinct_id: '123',
event: '$groupidentify',
properties: {
$group_type: 'posthog',
$group_key: 'team-1',
$group_set: { analytics: true },
$lib: 'posthog-node',
$geoip_disable: true,
},
},
])
})
})
describe('feature flags', () => {
beforeEach(() => {
const mockFeatureFlags = {
'feature-1': true,
'feature-2': true,
'feature-variant': 'variant',
'disabled-flag': false,
'feature-array': true,
}
// these are stringified in apiImplementation
const mockFeatureFlagPayloads = {
'feature-1': { color: 'blue' },
'feature-variant': 2,
'feature-array': [1],
}
const multivariateFlag = {
id: 1,
name: 'Beta Feature',
key: 'beta-feature-local',
active: true,
rollout_percentage: 100,
filters: {
groups: [
{
properties: [{ key: 'email', type: 'person', value: 'test@posthog.com', operator: 'exact' }],
rollout_percentage: 100,
},
{
rollout_percentage: 50,
},
],
multivariate: {
variants: [
{ key: 'first-variant', name: 'First Variant', rollout_percentage: 50 },
{ key: 'second-variant', name: 'Second Variant', rollout_percentage: 25 },
{ key: 'third-variant', name: 'Third Variant', rollout_percentage: 25 },
],
},
payloads: { 'first-variant': 'some-payload', 'third-variant': JSON.stringify({ a: 'json' }) },
},
}
const basicFlag = {
id: 1,
name: 'Beta Feature',
key: 'person-flag',
active: true,
filters: {
groups: [
{
properties: [
{
key: 'region',
operator: 'exact',
value: ['USA'],
type: 'person',
},
],
rollout_percentage: 100,
},
],
payloads: { true: '300' },
},
}
const falseFlag = {
id: 1,
name: 'Beta Feature',
key: 'false-flag',
active: true,
filters: {
groups: [
{
properties: [],
rollout_percentage: 0,
},
],
payloads: { true: '300' },
},
}
const arrayFlag = {
id: 5,
name: 'Beta Feature',
key: 'feature-array',
active: true,
filters: {
groups: [
{
properties: [],
rollout_percentage: 100,
},
],
payloads: { true: JSON.stringify([1]) },
},
}
mockedFetch.mockImplementation(
apiImplementation({
decideFlags: mockFeatureFlags,
flagsPayloads: mockFeatureFlagPayloads,
localFlags: { flags: [multivariateFlag, basicFlag, falseFlag, arrayFlag] },
})
)
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
disableCompression: true,
})
})
it('should do getFeatureFlag', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
await expect(posthog.getFeatureFlag('feature-variant', '123', { groups: { org: '123' } })).resolves.toEqual(
'variant'
)
expect(mockedFetch).toHaveBeenCalledTimes(1)
expect(mockedFetch).toHaveBeenCalledWith(
'http://example.com/flags/?v=2',
expect.objectContaining({ method: 'POST', body: expect.stringContaining('"geoip_disable":true') })
)
})
it('should do isFeatureEnabled', async () => {
expect(mockedFetch).toHaveBeenCalledTimes(0)
await expect(posthog.isFeatureEnabled('feature-1', '123', { groups: { org: '123' } })).resolves.toEqual(true)
await expect(posthog.isFeatureEnabled('feature-4', '123', { groups: { org: '123' } })).resolves.toEqual(undefined)
expect(mockedFetch).toHaveBeenCalledTimes(2)
})
it('captures feature flags when no personal API key is present', async () => {
mockedFetch.mockClear()
mockedFetch.mockClear()
expect(mockedFetch).toHaveBeenCalledTimes(0)
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
flushAt: 1,
fetchRetryCount: 0,
disableCompression: true,
})
posthog.capture({
distinctId: 'distinct_id',
event: 'node test event',
sendFeatureFlags: true,
})
jest.runOnlyPendingTimers()
await waitForPromises()
expect(mockedFetch).toHaveBeenCalledWith(
'http://example.com/flags/?v=2',
expect.objectContaining({ method: 'POST' })
)
expect(getLastBatchEvents()?.[0]).toEqual(
expect.objectContaining({
distinct_id: 'distinct_id',
event: 'node test event',
properties: expect.objectContaining({
$active_feature_flags: ['feature-1', 'feature-2', 'feature-array', 'feature-variant'],
'$feature/feature-1': true,
'$feature/feature-2': true,
'$feature/feature-array': true,
'$feature/feature-variant': 'variant',
$lib: 'posthog-node',
$lib_version: '1.2.3',
$geoip_disable: true,
}),
})
)
// no calls to `/local_evaluation`
expect(mockedFetch).not.toHaveBeenCalledWith(...anyLocalEvalCall)
expect(mockedFetch).toHaveBeenCalledWith(
'http://example.com/flags/?v=2',
expect.objectContaining({ method: 'POST', body: expect.stringContaining('"geoip_disable":true') })
)
})
it('should use minimum featureFlagsPollingInterval of 100ms if set less to less than 100', async () => {
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
personalApiKey: 'TEST_PERSONAL_API_KEY',
featureFlagsPollingInterval: 98,
disableCompression: true,
})
expect(posthog.options.featureFlagsPollingInterval).toEqual(100)
})
it('should use default featureFlagsPollingInterval of 30000ms if none provided', async () => {
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
personalApiKey: 'TEST_PERSONAL_API_KEY',
disableCompression: true,
})
expect(posthog.options.featureFlagsPollingInterval).toEqual(30000)
})
it('should throw an error when creating SDK if a project key is passed in as personalApiKey', async () => {
expect(() => {
posthog = new PostHog('TEST_API_KEY', {
host: 'http://example.com',
fetchRetryCount: 0,
personalApiKey: 'phc_abc123',
featureFlagsPollingInterval: 100,
disableCompression: true,
})
}).toThrow(Error)
})
it('does not automatically enrich capture events with flags unless sendFeatureFlags=true', async () => {
mockedFetch.mockClear()
expect(mockedFetch).toHaveBeenCalledTimes(0)