From f9a374c0aa21636e4f3ebde0458de64fe4985f10 Mon Sep 17 00:00:00 2001 From: Ben White Date: Wed, 24 Apr 2024 17:25:28 +0200 Subject: [PATCH] Add tests --- src/__tests__/heatmaps.test.ts | 36 ++++++++++++++++++++++++++++++++++ src/heatmaps.ts | 10 +++++----- 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/__tests__/heatmaps.test.ts b/src/__tests__/heatmaps.test.ts index 9432dbde1..4d86051dd 100644 --- a/src/__tests__/heatmaps.test.ts +++ b/src/__tests__/heatmaps.test.ts @@ -1,6 +1,8 @@ import { createPosthogInstance } from './helpers/posthog-instance' import { uuidv7 } from '../uuidv7' import { PostHog } from '../posthog-core' +import { HEATMAPS_ENABLED_SERVER_SIDE } from '../constants' +import { DecideResponse } from '../types' jest.mock('../utils/logger') describe('heatmaps', () => { @@ -105,4 +107,38 @@ describe('heatmaps', () => { ) expect(posthog.heatmaps?.['buffer']).not.toEqual(undefined) }) + + describe('afterDecideResponse()', () => { + it('should not be enabled before the decide response', () => { + expect(posthog.heatmaps!.isEnabled).toBe(false) + }) + + it('should be enabled if client config option is enabled', () => { + posthog.config.__preview_heatmaps = true + expect(posthog.heatmaps!.isEnabled).toBe(true) + }) + + it.each([ + // Client not defined + [undefined, false, false], + [undefined, true, true], + [undefined, false, false], + // Client false + [false, false, false], + [false, true, false], + + // Client true + [true, false, true], + [true, true, true], + ])( + 'when client side config is %p and remote opt in is %p - heatmaps enabled should be %p', + (clientSideOptIn, serverSideOptIn, expected) => { + posthog.config.__preview_heatmaps = clientSideOptIn + posthog.heatmaps!.afterDecideResponse({ + heatmaps: serverSideOptIn, + } as DecideResponse) + expect(posthog.heatmaps!.isEnabled).toBe(expected) + } + ) + }) }) diff --git a/src/heatmaps.ts b/src/heatmaps.ts index 620dd9f54..987ce5fe1 100644 --- a/src/heatmaps.ts +++ b/src/heatmaps.ts @@ -6,6 +6,7 @@ import { PostHog } from './posthog-core' import { document, window } from './utils/globals' import { getParentElement, isTag } from './autocapture-utils' import { HEATMAPS_ENABLED_SERVER_SIDE } from './constants' +import { isUndefined } from './utils/type-utils' type HeatmapEventBuffer = | { @@ -50,6 +51,7 @@ export class Heatmaps { constructor(instance: PostHog) { this.instance = instance + this._enabledServerSide = !!this.instance.persistence?.props[HEATMAPS_ENABLED_SERVER_SIDE] } public startIfEnabled(): void { @@ -59,11 +61,9 @@ export class Heatmaps { } public get isEnabled(): boolean { - return ( - !!this.instance.config.__preview_heatmaps || - !!this._enabledServerSide || - !!this.instance.persistence?.props[HEATMAPS_ENABLED_SERVER_SIDE] - ) + return !isUndefined(this.instance.config.__preview_heatmaps) + ? this.instance.config.__preview_heatmaps + : this._enabledServerSide } public afterDecideResponse(response: DecideResponse) {