-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalytics.test.ts
More file actions
62 lines (53 loc) · 2.34 KB
/
analytics.test.ts
File metadata and controls
62 lines (53 loc) · 2.34 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
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PosthogEventCapture, EventCaptureError } from '../src/analytics';
describe('PosthogEventCapture', () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it('does nothing when POSTHOG_API_HOST is missing', async () => {
const fetchSpy = vi.spyOn(global, 'fetch');
const capture = new PosthogEventCapture({ POSTHOG_API_KEY: 'key' });
await capture.capture('test_event');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('does nothing when POSTHOG_API_KEY is missing', async () => {
const fetchSpy = vi.spyOn(global, 'fetch');
const capture = new PosthogEventCapture({ POSTHOG_API_HOST: 'https://posthog.example.com' });
await capture.capture('test_event');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('sends a POST request to the capture endpoint', async () => {
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));
const capture = new PosthogEventCapture({
POSTHOG_API_HOST: 'https://posthog.example.com',
POSTHOG_API_KEY: 'phc_testkey',
});
await capture.capture('db_created', { region: 'us-east-1' });
expect(fetchSpy).toHaveBeenCalledOnce();
const [url, init] = fetchSpy.mock.calls[0];
expect(url).toBe('https://posthog.example.com/capture');
expect(init?.method).toBe('POST');
const body = JSON.parse(init?.body as string);
expect(body.event).toBe('db_created');
expect(body.properties.region).toBe('us-east-1');
expect(body.properties.$process_person_profile).toBe(false);
});
it('strips trailing slash from host', async () => {
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue(new Response(null, { status: 200 }));
const capture = new PosthogEventCapture({
POSTHOG_API_HOST: 'https://posthog.example.com///',
POSTHOG_API_KEY: 'key',
});
await capture.capture('event');
const [url] = fetchSpy.mock.calls[0];
expect(url).toBe('https://posthog.example.com/capture');
});
it('throws EventCaptureError on non-ok response', async () => {
vi.spyOn(global, 'fetch').mockResolvedValue(new Response(null, { status: 500, statusText: 'Internal Server Error' }));
const capture = new PosthogEventCapture({
POSTHOG_API_HOST: 'https://posthog.example.com',
POSTHOG_API_KEY: 'key',
});
await expect(capture.capture('event')).rejects.toBeInstanceOf(EventCaptureError);
});
});