feat(core-testing): add RecordingAnalytics test double
Implements IAnalytics with recorded arrays (tracked, identified, pageViewed) and flush() that drains the buffer. Mirrors the pattern established by RecordingAuditLog; inline type aliases avoid a build-graph cycle with @repo/core-analytics. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { RecordingAnalytics } from "./recording-analytics";
|
||||
|
||||
describe("RecordingAnalytics", () => {
|
||||
it("track() pushes to tracked[]", () => {
|
||||
const analytics = new RecordingAnalytics();
|
||||
analytics.track("button_clicked", { page: "home" });
|
||||
expect(analytics.tracked).toHaveLength(1);
|
||||
expect(analytics.tracked[0]!.event).toBe("button_clicked");
|
||||
expect(analytics.tracked[0]!.attributes).toEqual({ page: "home" });
|
||||
});
|
||||
|
||||
it("identify() pushes to identified[]", () => {
|
||||
const analytics = new RecordingAnalytics();
|
||||
analytics.identify({ id: "user_1" }, { plan: "pro" });
|
||||
expect(analytics.identified).toHaveLength(1);
|
||||
expect(analytics.identified[0]!.user).toEqual({ id: "user_1" });
|
||||
expect(analytics.identified[0]!.attributes).toEqual({ plan: "pro" });
|
||||
});
|
||||
|
||||
it("pageView() pushes to pageViewed[]", () => {
|
||||
const analytics = new RecordingAnalytics();
|
||||
analytics.pageView("/home", { referrer: "google" });
|
||||
expect(analytics.pageViewed).toHaveLength(1);
|
||||
expect(analytics.pageViewed[0]!.path).toBe("/home");
|
||||
expect(analytics.pageViewed[0]!.attributes).toEqual({ referrer: "google" });
|
||||
});
|
||||
|
||||
it("flush() drains all arrays and resolves", async () => {
|
||||
const analytics = new RecordingAnalytics();
|
||||
analytics.track("event_1");
|
||||
analytics.identify({ id: "user_1" });
|
||||
analytics.pageView("/about");
|
||||
await analytics.flush();
|
||||
expect(analytics.tracked).toEqual([]);
|
||||
expect(analytics.identified).toEqual([]);
|
||||
expect(analytics.pageViewed).toEqual([]);
|
||||
});
|
||||
|
||||
it("methods accept calls without attributes", () => {
|
||||
const analytics = new RecordingAnalytics();
|
||||
analytics.track("no_attrs");
|
||||
analytics.identify({ id: "user_2" });
|
||||
analytics.pageView("/contact");
|
||||
expect(analytics.tracked[0]!.attributes).toBeUndefined();
|
||||
expect(analytics.identified[0]!.attributes).toBeUndefined();
|
||||
expect(analytics.pageViewed[0]!.attributes).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user