posthog.test.ts60 lines · main
1import * as common from 'common'
2import { beforeEach, describe, expect, it, vi } from 'vitest'
3
4import * as constants from './constants'
5import { trackFeatureFlag } from './posthog'
6import * as fetchers from '@/data/fetchers'
7
8vi.mock('@/data/fetchers', () => ({
9 post: vi.fn(),
10 handleError: vi.fn(),
11}))
12vi.mock('common', () => ({
13 hasConsented: vi.fn(),
14 LOCAL_STORAGE_KEYS: {},
15}))
16vi.mock('./constants', () => ({
17 IS_PLATFORM: true,
18}))
19
20describe('trackFeatureFlag', () => {
21 beforeEach(() => {
22 vi.clearAllMocks()
23 })
24
25 it('returns undefined if user has not consented', async () => {
26 vi.spyOn(common, 'hasConsented').mockReturnValue(false)
27 const result = await trackFeatureFlag({ some: 'value' } as any)
28 expect(result).toBeUndefined()
29 })
30
31 it('returns undefined if not on platform', async () => {
32 vi.spyOn(common, 'hasConsented').mockReturnValue(true)
33 vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(false)
34 const result = await trackFeatureFlag({ some: 'value' } as any)
35 expect(result).toBeUndefined()
36 })
37
38 it('calls post with correct body if consented and on platform', async () => {
39 vi.spyOn(common, 'hasConsented').mockReturnValue(true)
40 vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(true)
41 vi.spyOn(fetchers, 'post').mockResolvedValue({ data: 'success' })
42
43 const result = await trackFeatureFlag({ foo: 'bar' } as any)
44
45 expect(fetchers.post).toHaveBeenCalledWith('/platform/telemetry/feature-flags/track', {
46 body: { foo: 'bar' },
47 })
48 expect(result).toBe('success')
49 })
50
51 it('calls handleError if post returns error', async () => {
52 vi.spyOn(common, 'hasConsented').mockReturnValue(true)
53 vi.spyOn(constants, 'IS_PLATFORM', 'get').mockReturnValue(true)
54 vi.spyOn(fetchers, 'post').mockResolvedValue({ error: { message: 'fail' } })
55
56 await trackFeatureFlag({ foo: 'bar' } as any)
57
58 expect(fetchers.handleError).toHaveBeenCalledWith({ message: 'fail' })
59 })
60})