feat(core-analytics): add React provider and useAnalytics hook
Adds a ./react subpath export to @repo/core-analytics containing
<AnalyticsProvider value={IAnalytics}> and useAnalytics(): IAnalytics.
useAnalytics() throws AnalyticsContextError when called outside a provider.
React Testing Library test verifies track() flows through context using
RecordingAnalytics. Switches vitest config to pick up .tsx test files
via environmentMatchGlobs and extends tsconfig to react-library.json
for JSX support.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, renderHook } from "@testing-library/react";
|
||||
import { RecordingAnalytics } from "@repo/core-testing";
|
||||
import {
|
||||
AnalyticsContextError,
|
||||
AnalyticsProvider,
|
||||
useAnalytics,
|
||||
} from "@/react/index";
|
||||
|
||||
function Tracker() {
|
||||
const analytics = useAnalytics();
|
||||
analytics.track("test.event");
|
||||
return null;
|
||||
}
|
||||
|
||||
describe("AnalyticsProvider", () => {
|
||||
it("makes analytics available through context and track flows through", () => {
|
||||
const recording = new RecordingAnalytics();
|
||||
|
||||
render(
|
||||
<AnalyticsProvider value={recording}>
|
||||
<Tracker />
|
||||
</AnalyticsProvider>,
|
||||
);
|
||||
|
||||
expect(recording.tracked).toContainEqual({ event: "test.event" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("useAnalytics", () => {
|
||||
it("throws AnalyticsContextError when called outside a provider", () => {
|
||||
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
try {
|
||||
expect(() => renderHook(() => useAnalytics())).toThrow(
|
||||
AnalyticsContextError,
|
||||
);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user