diff --git a/src/__tests__/loader.test.ts b/src/__tests__/loader.test.ts index 81165a32b..b5319dc85 100644 --- a/src/__tests__/loader.test.ts +++ b/src/__tests__/loader.test.ts @@ -5,7 +5,7 @@ * currently not supported in the browser lib). */ -import posthog from '../loader-module' +import posthog, { PostHog } from '../loader-module' import sinon from 'sinon' import { window } from '../utils/globals' @@ -48,4 +48,22 @@ describe(`Module-based loader in Node env`, () => { it(`supports capture()`, () => { expect(() => posthog.capture(`Pat`)).not.toThrow() }) + + it(`always returns posthog from init`, () => { + console.error = jest.fn() + console.warn = jest.fn() + expect(posthog.init(`my-test`, undefined, 'sdk-1')).toBeInstanceOf(PostHog) + expect(posthog.init(``, undefined, 'sdk-2')).toBeInstanceOf(PostHog) + expect(console.error).toHaveBeenCalledTimes(1) + expect(console.error).toHaveBeenCalledWith( + '[PostHog.js]', + 'PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()' + ) + // Already loaded + expect(posthog.init(`my-test`, undefined, 'sdk-1')).toBeInstanceOf(PostHog) + expect(console.warn).toHaveBeenCalledWith( + '[PostHog.js]', + 'You have already initialized PostHog! Re-initializing is a no-op' + ) + }) }) diff --git a/src/posthog-core.ts b/src/posthog-core.ts index 0b6b4688e..853ce7160 100644 --- a/src/posthog-core.ts +++ b/src/posthog-core.ts @@ -273,7 +273,7 @@ export class PostHog { */ init(token: string, config?: Partial, name?: string): PostHog | void { if (!name || name === PRIMARY_INSTANCE_NAME) { - // This means we are initialising the primary instance (i.e. this) + // This means we are initializing the primary instance (i.e. this) return this._init(token, config, name) } else { const namedPosthog = instances[name] ?? new PostHog() @@ -299,17 +299,17 @@ export class PostHog { // IE11 compatible. We could use polyfills, which would make the // code a bit cleaner, but will add some overhead. // - _init(token: string, config: Partial = {}, name?: string): PostHog | void { + _init(token: string, config: Partial = {}, name?: string): PostHog { if (_isUndefined(token) || _isEmptyString(token)) { logger.critical( 'PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()' ) - return + return this } if (this.__loaded) { - logger.warn('You have already initialized PostHog! Re-initialising is a no-op') - return + logger.warn('You have already initialized PostHog! Re-initializing is a no-op') + return this } this.__loaded = true