diff --git a/lib/__tests__/init.test.ts b/lib/__tests__/init.test.ts index 48dbe18f..23cd4c80 100644 --- a/lib/__tests__/init.test.ts +++ b/lib/__tests__/init.test.ts @@ -1,10 +1,12 @@ import AlgoliaAnalytics from "../insights"; import * as utils from "../utils"; +import { getCookie } from "../_cookieUtils"; describe("init", () => { let analyticsInstance; beforeEach(() => { analyticsInstance = new AlgoliaAnalytics({ requestFn: () => {} }); + document.cookie = `_ALGOLIA=;${new Date().toUTCString()};path=/`; }); it("should throw if no parameters is passed", () => { @@ -63,6 +65,15 @@ describe("init", () => { }); expect(analyticsInstance._userHasOptedOut).toBe(true); }); + it("should not set anonymous user token when _userHasOptedOut is true", () => { + analyticsInstance.init({ + apiKey: "***", + appId: "XXX", + userHasOptedOut: true + }); + expect(analyticsInstance._userToken).toBeUndefined(); + expect(getCookie("_ALGOLIA")).toBe(""); + }); it("should use 6 months cookieDuration by default", () => { analyticsInstance.init({ apiKey: "***", appId: "XXX" }); const month = 30 * 24 * 60 * 60 * 1000; diff --git a/lib/init.ts b/lib/init.ts index 48fb2a96..5b93ce0e 100644 --- a/lib/init.ts +++ b/lib/init.ts @@ -72,7 +72,7 @@ export function init(options: InitParams) { this._ua = DEFAULT_ALGOLIA_AGENT; this._uaURIEncoded = encodeURIComponent(DEFAULT_ALGOLIA_AGENT); - if (supportsCookies()) { + if (!this._userHasOptedOut && supportsCookies()) { this.setUserToken(this.ANONYMOUS_USER_TOKEN); } }