Skip to content

Commit

Permalink
Move tsconfig to test folder, get tests passing type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
robbie-c committed Aug 13, 2024
1 parent 331201f commit c9045ea
Show file tree
Hide file tree
Showing 19 changed files with 104 additions and 85 deletions.
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@
"lint": "eslint src && eslint cypress",
"prettier": "prettier --write src/ functional_tests/",
"prepublishOnly": "pnpm lint && pnpm test && pnpm build && pnpm test:react",
"test": "pnpm typecheck && pnpm test:unit && pnpm test:custom-eslint-rules && pnpm test:functional",
"test": "pnpm test:unit && pnpm test:custom-eslint-rules && pnpm test:functional",
"test:unit": "jest src",
"test:custom-eslint-rules": "jest eslint-rules",
"test:react": "cd react; pnpm test",
"test:functional": "jest functional_tests",
"test-watch": "jest --watch src",
"typecheck": "tsc --noEmit --project tsconfig.test.json",
"test:typecheck": "cd src/__tests__ && tsc --noEmit --project tsconfig.json",
"typecheck": "tsc --noEmit --project tsconfig.json",
"cypress": "cypress open",
"prepare": "husky install",
"deprecate-old-versions": "node scripts/deprecate-old-versions.mjs"
"deprecate-old-versions": "node scripts/deprecate-old-versions.mjs",
"tsc": "tsc"
},
"main": "dist/main.js",
"module": "dist/module.js",
Expand All @@ -34,6 +36,7 @@
"react/package.json"
],
"dependencies": {
"@types/web": "^0.0.154",
"fflate": "^0.4.8",
"preact": "^10.19.3",
"web-vitals": "^4.0.1"
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/__tests__/consent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ function deleteAllCookies() {

describe('consentManager', () => {
const createPostHog = (config: Partial<PostHogConfig> = {}) => {
const posthog = defaultPostHog().init('testtoken', { ...config }, uuidv7())!
const posthog = defaultPostHog().init('testtoken', { ...config }, uuidv7())
if (!posthog) {
throw new Error('Failed to initialize PostHog')
}
posthog.debug()
return posthog
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

import {
errorToProperties,
ErrorProperties,
unhandledRejectionToProperties,
} from '../../../extensions/exception-autocapture/error-conversion'

import { isNull } from '../../../utils/type-utils'
import { expect } from '@jest/globals'
import { ErrorProperties } from '../../../types'

// ugh, jest
// can't reference PromiseRejectionEvent to construct it 🤷
Expand Down
22 changes: 13 additions & 9 deletions src/__tests__/featureflags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,30 @@
import { filterActiveFeatureFlags, parseFeatureFlagDecideResponse, PostHogFeatureFlags } from '../posthog-featureflags'
import { PostHogPersistence } from '../posthog-persistence'
import { RequestRouter } from '../utils/request-router'
import { PostHogConfig } from '../types'

jest.useFakeTimers()
jest.spyOn(global, 'setTimeout')

describe('featureflags', () => {
let instance: any
let featureFlags: any
let instance
let featureFlags

const config = {
token: 'random fake token',
persistence: 'memory',
api_host: 'https://app.posthog.com',
}
} as PostHogConfig

let mockWarn

beforeEach(() => {
instance = {
config,
get_distinct_id: () => 'blah id',
getGroups: () => {},
persistence: new PostHogPersistence(config),
requestRouter: new RequestRouter({ config }),
requestRouter: new RequestRouter({ config } as any),
register: (props) => instance.persistence.register(props),
unregister: (key) => instance.persistence.unregister(key),
get_property: (key) => instance.persistence.props[key],
Expand All @@ -40,8 +43,8 @@ describe('featureflags', () => {

featureFlags = new PostHogFeatureFlags(instance)

jest.spyOn(instance, 'capture').mockReturnValue()
jest.spyOn(window.console, 'warn').mockImplementation()
jest.spyOn(instance, 'capture').mockReturnValue(undefined)
mockWarn = jest.spyOn(window.console, 'warn').mockImplementation()

instance.persistence.register({
$feature_flag_payloads: {
Expand Down Expand Up @@ -76,7 +79,7 @@ describe('featureflags', () => {
})

it('should warn if decide endpoint was not hit and no flags exist', () => {
window.POSTHOG_DEBUG = true
;(window as any).POSTHOG_DEBUG = true
featureFlags.instance.decideEndpointWasHit = false
instance.persistence.unregister('$enabled_feature_flags')
instance.persistence.unregister('$active_feature_flags')
Expand All @@ -88,7 +91,7 @@ describe('featureflags', () => {
'isFeatureEnabled for key "beta-feature" failed. Feature flags didn\'t load in time.'
)

window.console.warn.mockClear()
mockWarn.mockClear()

expect(featureFlags.getFeatureFlag('beta-feature')).toEqual(undefined)
expect(window.console.warn).toHaveBeenCalledWith(
Expand Down Expand Up @@ -249,7 +252,7 @@ describe('featureflags', () => {
)

// Clear the mock to reset call count
window.console.warn.mockClear()
mockWarn.mockClear()

// Test with suppressing warning (new behavior)
featureFlags.override(
Expand Down Expand Up @@ -1031,6 +1034,7 @@ describe('parseFeatureFlagDecideResponse', () => {
// checks that nothing fails when asking for ?v=2 and getting a ?v=1 response
const decideResponse = { featureFlags: ['beta-feature', 'alpha-feature-2'] }

// @ts-expect-error testing backwards compatibility
parseFeatureFlagDecideResponse(decideResponse, persistence)

expect(persistence.register).toHaveBeenLastCalledWith({
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/helpers/script-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const checkScriptsForSrcExists = (src: string): boolean => {
const scripts = document.querySelectorAll('body > script')
let foundScript = false
for (let i = 0; i < scripts.length; i++) {
if (scripts[i].src === src) {
if ((scripts[i] as any).src === src) {
foundScript = true
break
}
Expand Down
40 changes: 20 additions & 20 deletions src/__tests__/posthog-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as globals from '../utils/globals'
import { USER_STATE } from '../constants'
import { createPosthogInstance, defaultPostHog } from './helpers/posthog-instance'
import { logger } from '../utils/logger'
import { PostHogConfig } from '../types'
import { DecideResponse, PostHogConfig } from '../types'
import { PostHog } from '../posthog-core'
import { PostHogPersistence } from '../posthog-persistence'
import { SessionIdManager } from '../sessionid'
Expand Down Expand Up @@ -141,6 +141,7 @@ describe('posthog core', () => {
const posthog = posthogWith(defaultConfig, defaultOverrides)
posthog._addCaptureHook(hook)

// @ts-expect-error - testing invalid input
expect(() => posthog.capture({ event: 'object as name' })).not.toThrow()
expect(hook).not.toHaveBeenCalled()
expect(logger.error).toHaveBeenCalledWith('No event name provided to posthog.capture')
Expand Down Expand Up @@ -298,7 +299,7 @@ describe('posthog core', () => {

it('sends payloads to alternative endpoint if given', () => {
const posthog = posthogWith({ ...defaultConfig, request_batching: false }, defaultOverrides)
posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } })
posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } } as DecideResponse)

posthog.capture('event-name', { foo: 'bar', length: 0 })

Expand All @@ -323,7 +324,7 @@ describe('posthog core', () => {

it('sends payloads to overriden _url, even if alternative endpoint is set', () => {
const posthog = posthogWith({ ...defaultConfig, request_batching: false }, defaultOverrides)
posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } })
posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } } as DecideResponse)

posthog.capture('event-name', { foo: 'bar', length: 0 }, { _url: 'https://app.posthog.com/s/' })

Expand All @@ -339,39 +340,39 @@ describe('posthog core', () => {
it('enables compression from decide response', () => {
const posthog = posthogWith({})

posthog._afterDecideResponse({ supportedCompression: ['gzip-js', 'base64'] })
posthog._afterDecideResponse({ supportedCompression: ['gzip-js', 'base64'] } as DecideResponse)

expect(posthog.compression).toEqual('gzip-js')
})

it('enables compression from decide response when only one received', () => {
const posthog = posthogWith({})

posthog._afterDecideResponse({ supportedCompression: ['base64'] })
posthog._afterDecideResponse({ supportedCompression: ['base64'] } as DecideResponse)

expect(posthog.compression).toEqual('base64')
})

it('does not enable compression from decide response if compression is disabled', () => {
const posthog = posthogWith({ disable_compression: true, persistence: 'memory' })

posthog._afterDecideResponse({ supportedCompression: ['gzip-js', 'base64'] })
posthog._afterDecideResponse({ supportedCompression: ['gzip-js', 'base64'] } as DecideResponse)

expect(posthog.compression).toEqual(undefined)
})

it('defaults to /e if no endpoint is given', () => {
const posthog = posthogWith({})

posthog._afterDecideResponse({})
posthog._afterDecideResponse({} as DecideResponse)

expect(posthog.analyticsDefaultEndpoint).toEqual('/e/')
})

it('uses the specified analytics endpoint if given', () => {
const posthog = posthogWith({})

posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } })
posthog._afterDecideResponse({ analytics: { endpoint: '/i/v0/e/' } } as DecideResponse)

expect(posthog.analyticsDefaultEndpoint).toEqual('/i/v0/e/')
})
Expand Down Expand Up @@ -414,7 +415,7 @@ describe('posthog core', () => {
})

it('returns calculated properties', () => {
expect(posthog._calculate_event_properties('custom_event', { event: 'prop' })).toEqual({
expect(posthog._calculate_event_properties('custom_event', { event: 'prop' }, new Date())).toEqual({
token: 'testtoken',
event: 'prop',
$lib: 'web',
Expand All @@ -435,7 +436,7 @@ describe('posthog core', () => {
overrides
)

expect(posthog._calculate_event_properties('custom_event', { event: 'prop' })).toEqual({
expect(posthog._calculate_event_properties('custom_event', { event: 'prop' }, new Date())).toEqual({
token: 'testtoken',
event: 'prop',
$lib: 'web',
Expand All @@ -460,7 +461,9 @@ describe('posthog core', () => {
)

expect(
posthog._calculate_event_properties('custom_event', { event: 'prop' })['$process_person_profile']
posthog._calculate_event_properties('custom_event', { event: 'prop' }, new Date())[
'$process_person_profile'
]
).toEqual(true)
})

Expand All @@ -472,7 +475,7 @@ describe('posthog core', () => {
overrides
)

expect(posthog._calculate_event_properties('$snapshot', { event: 'prop' })).toEqual({
expect(posthog._calculate_event_properties('$snapshot', { event: 'prop' }, new Date())).toEqual({
token: 'testtoken',
event: 'prop',
distinct_id: 'abc',
Expand All @@ -489,7 +492,7 @@ describe('posthog core', () => {
overrides
)

expect(posthog._calculate_event_properties('custom_event', { event: 'prop' })).toEqual({
expect(posthog._calculate_event_properties('custom_event', { event: 'prop' }, new Date())).toEqual({
event_name: 'custom_event',
token: 'testtoken',
$process_person_profile: true,
Expand All @@ -499,7 +502,7 @@ describe('posthog core', () => {
it('saves $snapshot data and token for $snapshot events', () => {
posthog = posthogWith({}, overrides)

expect(posthog._calculate_event_properties('$snapshot', { $snapshot_data: {} })).toEqual({
expect(posthog._calculate_event_properties('$snapshot', { $snapshot_data: {} }, new Date())).toEqual({
token: 'testtoken',
$snapshot_data: {},
distinct_id: 'abc',
Expand All @@ -509,15 +512,15 @@ describe('posthog core', () => {
it("doesn't modify properties passed into it", () => {
const properties = { prop1: 'val1', prop2: 'val2' }

posthog._calculate_event_properties('custom_event', properties)
posthog._calculate_event_properties('custom_event', properties, new Date())

expect(Object.keys(properties)).toEqual(['prop1', 'prop2'])
})

it('adds page title to $pageview', () => {
document!.title = 'test'

expect(posthog._calculate_event_properties('$pageview', {})).toEqual(
expect(posthog._calculate_event_properties('$pageview', {}, new Date())).toEqual(
expect.objectContaining({ title: 'test' })
)
})
Expand Down Expand Up @@ -772,13 +775,10 @@ describe('posthog core', () => {
})

describe('init()', () => {
// @ts-expect-error - it's fine to spy on window
jest.spyOn(window, 'window', 'get')

beforeEach(() => {
// @ts-expect-error - it's fine to spy on window
jest.spyOn(window.console, 'warn').mockImplementation()
// @ts-expect-error - it's fine to spy on window
jest.spyOn(window.console, 'error').mockImplementation()
})

Expand All @@ -794,7 +794,7 @@ describe('posthog core', () => {
// TODO this didn't make a tonne of sense in the given form
// it makes no sense now
// of course mocks added _after_ init will not be called
const posthog = defaultPostHog().init('testtoken', defaultConfig, uuidv7())!
const posthog = defaultPostHog().init('testtoken', defaultConfig, uuidv7())

posthog.sessionRecording = {
afterDecideResponse: jest.fn(),
Expand Down
Loading

0 comments on commit c9045ea

Please sign in to comment.