:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import posthog, { CaptureResult, PostHogConfig } from 'posthog-js'
import { AppContext } from '~/types'
import { LastSeenFeatureFlags, loadPostHogJS, withLastSeenFeatureFlags } from './loadPostHogJS'
describe('loadPostHogJS', () => {
describe('withLastSeenFeatureFlags', () => {
const serverFlags = { 'server-decided': false, variant: 'control' }
it.each<{
case: string
lastSeen: LastSeenFeatureFlags | null
bootstrapFlags: LastSeenFeatureFlags['featureFlags'] | null | undefined
expected: LastSeenFeatureFlags['featureFlags'] | undefined
}>([
{
case: 'fills flags the server left out, and server values win',
lastSeen: { distinctId: 'user-a', featureFlags: { 'server-decided': true, 'staff-only': true } },
bootstrapFlags: serverFlags,
expected: { 'server-decided': false, variant: 'control', 'staff-only': true },
},
{
case: 'ignores flags another user saw on this browser',
lastSeen: { distinctId: 'user-b', featureFlags: { 'staff-only': true } },
bootstrapFlags: serverFlags,
expected: serverFlags,
},
{
case: 'keeps an empty bootstrap empty so posthog-js uses its own persisted flags',
lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },
bootstrapFlags: {},
expected: {},
},
{
case: 'keeps missing bootstrap flags absent when the same user has cached flags',
lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },
bootstrapFlags: undefined,
expected: undefined,
},
{
case: 'ignores null bootstrap flags when the same user has cached flags',
lastSeen: { distinctId: 'user-a', featureFlags: { 'staff-only': true } },
bootstrapFlags: null,
expected: undefined,
},
{
case: 'keeps the server flags when nothing is cached',
lastSeen: null,
bootstrapFlags: serverFlags,
expected: serverFlags,
},
])('$case', ({ lastSeen, bootstrapFlags, expected }) => {
expect(withLastSeenFeatureFlags({ featureFlags: bootstrapFlags }, lastSeen, 'user-a').featureFlags).toEqual(
expected
)
})
})
describe('without a project key', () => {
it('starts posthog-js with no request to PostHog', () => {
window.JS_POSTHOG_API_KEY = undefined
loadPostHogJS()
expect(posthog.init).toHaveBeenCalledWith(
'fake_token',
expect.objectContaining({ advanced_disable_flags: true, opt_out_capturing_by_default: true })
)
})
})
function initConfigFor(context: Partial<AppContext> | undefined, selfCapture: boolean): Partial<PostHogConfig> {
const original = {
key: window.JS_POSTHOG_API_KEY,
host: window.JS_POSTHOG_HOST,
selfCapture: window.JS_POSTHOG_SELF_CAPTURE,
context: window.POSTHOG_APP_CONTEXT,
}
window.JS_POSTHOG_API_KEY = 'phc_example'
window.JS_POSTHOG_HOST = window.location.origin
window.JS_POSTHOG_SELF_CAPTURE = selfCapture
window.POSTHOG_APP_CONTEXT = context as AppContext | undefined
jest.mocked(posthog.get_session_id).mockReturnValue('example-session')
jest.mocked(posthog.init).mockClear()
try {
loadPostHogJS()
return jest.mocked(posthog.init).mock.calls[0][1] ?? {}
} finally {
window.JS_POSTHOG_API_KEY = original.key
window.JS_POSTHOG_HOST = original.host
window.JS_POSTHOG_SELF_CAPTURE = original.selfCapture
window.POSTHOG_APP_CONTEXT = original.context
}
}
it.each([
['hobby with self-capture', { run_mode: 'HOBBY' }, true, false],
['hobby with Cloud assets', { run_mode: 'HOBBY' }, false, undefined],
['US cloud', { run_mode: 'US' }, false, undefined],
['EU cloud', { run_mode: 'EU' }, false, undefined],
['cloud development', { run_mode: 'DEV' }, false, undefined],
['local development', { run_mode: 'LOCAL' }, false, undefined],
['E2E', { run_mode: 'E2E' }, false, undefined],
['older app context', {}, false, undefined],
['missing app context', undefined, false, undefined],
] as const)('selects script versioning for %s', (_, context, selfCapture, expected) => {
const config = initConfigFor(context, selfCapture)
if (expected === undefined) {
expect(config).not.toHaveProperty('strict_script_versioning')
} else {
expect(config).toHaveProperty('strict_script_versioning', expected)
}
})
it.each([
['local development sending to Cloud', { run_mode: 'LOCAL' }, false, false],
['local development with self-capture', { run_mode: 'LOCAL' }, true, true],
['US cloud', { run_mode: 'US' }, false, true],
['hobby with Cloud assets', { run_mode: 'HOBBY' }, false, true],
] as const)('filters exceptions for %s', (_, context, selfCapture, sent) => {
const beforeSend = [initConfigFor(context, selfCapture).before_send ?? []].flat()
const exception = { uuid: 'example', event: '$exception', properties: {} } as CaptureResult
const pageview = { ...exception, event: '$pageview' }
const runFilters = (event: CaptureResult): CaptureResult | null =>
beforeSend.reduce<CaptureResult | null>((current, filter) => (current ? filter(current) : null), event)
expect(runFilters(exception) !== null).toBe(sent)
expect(runFilters(pageview)).not.toBeNull()
})
})