Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions src/detector.bootstrap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

describe("detector bootstrap", () => {
beforeEach(() => {
vi.resetModules();
vi.restoreAllMocks();
document.body.innerHTML = "";
document.cookie = "";
});

afterEach(() => {
vi.restoreAllMocks();
});

test("does nothing when already loaded", async () => {
const observe = vi.fn();
class MutationObserverMock {
observe = observe;
}
Object.defineProperty(window, "MutationObserver", {
configurable: true,
writable: true,
value: MutationObserverMock,
});

window.TS = {
token: "token",
loaded: true,
};

await import("./detector");
expect(observe).not.toHaveBeenCalled();
});

test("logs when token is missing", async () => {
const observe = vi.fn();
class MutationObserverMock {
observe = observe;
}
Object.defineProperty(window, "MutationObserver", {
configurable: true,
writable: true,
value: MutationObserverMock,
});

const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
window.TS = {} as typeof window.TS;

await import("./detector");
expect(error).toHaveBeenCalledWith("Missing TS token");
expect(observe).not.toHaveBeenCalled();
});

test("registers DOMContentLoaded listener when document is loading", async () => {
const readyStateDescriptor = Object.getOwnPropertyDescriptor(document, "readyState");
Object.defineProperty(document, "readyState", {
configurable: true,
get: () => "loading",
});

const addEventListenerSpy = vi.spyOn(window, "addEventListener");
window.TS = {
token: "token",
};

await import("./detector");
expect(addEventListenerSpy).toHaveBeenCalledWith("DOMContentLoaded", expect.any(Function));

if (readyStateDescriptor) {
Object.defineProperty(document, "readyState", readyStateDescriptor);
} else {
delete (document as { readyState?: string }).readyState;
}
});

test("uses hash router path when hash starts with slash", async () => {
window.TS = {
token: "token",
};
window.history.replaceState({}, "", "/checkout#/products/list");
document.body.innerHTML = '<div id="product" data-ts-product="product-id-hash"></div>';

const events: Array<{ page?: string }> = [];
window.addEventListener("topsort", (event) => {
events.push((event as CustomEvent).detail);
});

await import("./detector");
const product = document.querySelector("#product");
product?.dispatchEvent(new Event("click", { bubbles: true }));

expect(events.some((event) => event.page === "#/products/list")).toBe(true);
});

test("uses IntersectionObserver and skips non-HTMLElement matches", async () => {
const unobserve = vi.fn();
const observe = vi.fn();
let callback: IntersectionObserverCallback | undefined;
class IntersectionObserverMock {
constructor(cb: IntersectionObserverCallback) {
callback = cb;
}
observe = observe.mockImplementation((node: Element) => {
callback?.([{ isIntersecting: true, target: node } as IntersectionObserverEntry], this);
});
unobserve = unobserve;
disconnect = vi.fn();
takeRecords = vi.fn(() => []);
root = null;
rootMargin = "";
thresholds = [0.5];
}
Object.defineProperty(window, "IntersectionObserver", {
configurable: true,
writable: true,
value: IntersectionObserverMock,
});

const mutationObserve = vi.fn();
class MutationObserverMock {
observe = mutationObserve;
disconnect = vi.fn();
takeRecords = vi.fn(() => []);
}
Object.defineProperty(window, "MutationObserver", {
configurable: true,
writable: true,
value: MutationObserverMock,
});

window.TS = { token: "token" };
document.body.innerHTML = `
<svg id="svg-product" data-ts-product="svg-product"></svg>
<div id="html-product" data-ts-product="html-product"></div>
`;
const events: Array<{ type: string; product?: string }> = [];
window.addEventListener("topsort", (event) => {
events.push((event as CustomEvent).detail);
});

await import("./detector");

expect(observe).toHaveBeenCalledWith(expect.any(HTMLElement));
expect(unobserve).toHaveBeenCalledWith(expect.any(HTMLElement));
expect(
events.some((event) => event.type === "Impression" && event.product === "html-product"),
).toBe(true);
expect(events.some((event) => event.product === "svg-product")).toBe(false);
});

test("ignores attribute mutations for non-HTMLElement targets", async () => {
const observe = vi.fn();
class MutationObserverMock {
private callback: MutationCallback;

constructor(cb: MutationCallback) {
this.callback = cb;
}

observe = observe.mockImplementation(() => {
const text = document.createTextNode("not-an-element");
this.callback([{ type: "attributes", target: text } as unknown as MutationRecord], this);
});
disconnect = vi.fn();
takeRecords = vi.fn(() => []);
}
Object.defineProperty(window, "MutationObserver", {
configurable: true,
writable: true,
value: MutationObserverMock,
});

window.TS = { token: "token" };
await import("./detector");

expect(observe).toHaveBeenCalledOnce();
});
});
135 changes: 135 additions & 0 deletions src/detector.reporting.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

const reportEventMock = vi.fn();
const topsortClientConfigs: Array<Record<string, unknown>> = [];

vi.mock("@topsort/sdk", () => ({
TopsortClient: class {
constructor(config: Record<string, unknown>) {
topsortClientConfigs.push(config);
}

reportEvent = reportEventMock;
},
}));

async function flushQueue() {
await vi.advanceTimersByTimeAsync(300);
await Promise.resolve();
}

describe("detector reporting", () => {
beforeEach(() => {
vi.resetModules();
vi.useFakeTimers();
reportEventMock.mockReset();
topsortClientConfigs.length = 0;
document.body.innerHTML = "";
localStorage.clear();
document.cookie = "";
window.TS = { token: "token" };
});

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});

test("reports click payload with inherited bid as additional attribution", async () => {
reportEventMock.mockResolvedValue({ retry: false });
document.body.innerHTML = `
<div id="promoted" data-ts-product="ad-1" data-ts-resolved-bid="bid-123"></div>
<div id="organic" data-ts-product="organic-1" data-ts-resolved-bid="inherit"></div>
`;

await import("./detector");

const promoted = document.querySelector("#promoted");
const organic = document.querySelector("#organic");
promoted?.dispatchEvent(new Event("click", { bubbles: true }));
organic?.dispatchEvent(new Event("click", { bubbles: true }));
await flushQueue();

const clickPayload = reportEventMock.mock.calls
.map(([payload]) => payload)
.find((payload) => "clicks" in (payload as Record<string, unknown>)) as {
clicks: Array<Record<string, unknown>>;
};

expect(clickPayload).toBeDefined();
expect(clickPayload.clicks).toHaveLength(1);
const firstClick = clickPayload.clicks[0];
expect(firstClick).toBeDefined();
if (!firstClick) {
throw new Error("Expected at least one click payload");
}
expect(firstClick).toMatchObject({
resolvedBidId: "bid-123",
additionalAttribution: { type: "product", id: "organic-1" },
});
expect(firstClick.entity).toBeUndefined();
const firstClientConfig = topsortClientConfigs[0];
expect(firstClientConfig).toBeDefined();
if (!firstClientConfig) {
throw new Error("Expected Topsort client config");
}
expect(firstClientConfig).toMatchObject({
apiKey: "token",
userAgent: expect.stringMatching(/^ts\.js\//),
});
});

test("reports purchase payload and maps item fields", async () => {
reportEventMock.mockResolvedValue({ retry: false });
const items = JSON.stringify([
{ product: "sku-1", quantity: 2, price: 19.5 },
{ product: "sku-2", quantity: 1, price: 5.0 },
]);
document.body.innerHTML = `<div data-ts-action="purchase" data-ts-items='${items}'></div>`;

await import("./detector");
await flushQueue();

const purchasePayload = reportEventMock.mock.calls
.map(([payload]) => payload)
.find((payload) => "purchases" in (payload as Record<string, unknown>)) as {
purchases: Array<Record<string, unknown>>;
};

expect(purchasePayload).toBeDefined();
expect(purchasePayload.purchases[0]).toMatchObject({
items: [
{ productId: "sku-1", quantity: 2, unitPrice: 19.5 },
{ productId: "sku-2", quantity: 1, unitPrice: 5.0 },
],
});
});

test("continues processing when reportEvent rejects", async () => {
reportEventMock.mockRejectedValue(new Error("network-error"));
document.body.innerHTML = `<div id="product" data-ts-product="p-1"></div>`;

await import("./detector");
const product = document.querySelector("#product");
product?.dispatchEvent(new Event("click", { bubbles: true }));
await flushQueue();

expect(reportEventMock).toHaveBeenCalled();
});

test("keeps retryable events in queue and retries them", async () => {
reportEventMock.mockResolvedValueOnce({ retry: true }).mockResolvedValue({ retry: false });
document.body.innerHTML = `<div id="product" data-ts-product="p-2"></div>`;

await import("./detector");
const product = document.querySelector("#product");
product?.dispatchEvent(new Event("click", { bubbles: true }));
await flushQueue();
await flushQueue();

const clickCalls = reportEventMock.mock.calls
.map(([payload]) => payload)
.filter((payload) => "clicks" in (payload as Record<string, unknown>));
expect(clickCalls.length).toBeGreaterThanOrEqual(2);
});
});
26 changes: 26 additions & 0 deletions src/queue.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { type Entry, type ProcessorResult, Queue } from "./queue";
import { MemoryStore } from "./store";

let processedEvents: Entry[] = [];
async function processor(chunk: Entry[]): Promise<ProcessorResult> {
Expand Down Expand Up @@ -120,3 +121,28 @@ test("simultaneous entries", async () => {
await flushPromises(250);
expectEmptyQueue(q);
});

test("falls back to memory store when localStorage probing fails", () => {
const setItemSpy = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
throw new Error("storage blocked");
});

const q = new Queue(processor);

expect((q as any)._store).toBeInstanceOf(MemoryStore);
setItemSpy.mockRestore();
});

test("marks entries done when processor throws", async () => {
const failingProcessor = vi.fn(async (_chunk: Entry[]) => {
throw new Error("processor failed");
});
const q = new Queue(failingProcessor);
const entry = { id: "id-throw", t: now() };

q.append(entry, { highPriority: true });
await flushPromises();

expect(failingProcessor).toHaveBeenCalledWith([entry]);
expectEmptyQueue(q);
});
Loading