posthog.test.ts 1.9 KB

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