Files
novalon-website/src/components/analytics/GoogleAnalytics.test.tsx
T
zhangxiang fb14bf70d3 fix(analytics): 分析 Cookie 改 opt-in,后台不加载 GA(DEF-09)
两处独立问题:

① 默认同意。`DEFAULT_PREFERENCES.analytics` 是 true,且 GA inline snippet 的
   `consent default` 直接写 `analytics_storage: 'granted'` ⇒ **未同意、乃至已拒绝
   的用户照样被采集**。改为默认 denied;同时在 `gtag('config')` 之前从
   localStorage 回放一次已存偏好 —— 否则「上一访次同意过」的用户会退化,
   因为 `updateConsentDetailed` 在 `window.gtag` 尚未定义时会被静默丢弃。

② 后台加载 GA。`/admin` 没有 CookieConsent 条,管理员也就没有表达同意的入口,
   但 GA 脚本照常挂载、每次点击都进 dataLayer。新增 `shouldRenderAnalytics()`,
   `/admin*` 返回 null。

判别性测试(各自负对照已做):
- 默认改回 granted ⇒ 「默认 consent 为 denied」转红
- `shouldRenderAnalytics` 改成恒 true ⇒ 「/admin 不加载 GA」转红
- `getDefaultPreferences().analytics` 断言同步改为 false
2026-11-25 09:00:03 +08:00

291 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @ts-nocheck
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
import { render, act, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
// Mock useSyncExternalStore to always return true (mounted in browser environment)
jest.mock('react', () => {
const actual = jest.requireActual('react') as Record<string, unknown>;
return {
...actual,
useSyncExternalStore: jest.fn(() => true),
};
});
// Set env var at module scope so it's available when module is first loaded
process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID = 'G-TEST123';
// ─── Mocks ───────────────────────────────────────────────────────────────
const mockPathname = jest.fn(() => '/');
const mockSearchParams = jest.fn(() => new URLSearchParams());
jest.mock('next/navigation', () => ({
usePathname: () => mockPathname(),
useSearchParams: () => mockSearchParams(),
}));
jest.mock('next/script', () => {
const MockScript = (props: { id?: string; src?: string; children?: string; strategy?: string; [key: string]: unknown }) => {
const { children, src, ...rest } = props;
if (children) {
return <script data-testid="next-script" data-inline="true" {...rest} dangerouslySetInnerHTML={{ __html: children }} />;
}
return <script data-testid="next-script" src={src} {...rest} />;
};
MockScript.displayName = 'MockScript';
return MockScript;
});
// ─── Helpers ─────────────────────────────────────────────────────────────
const gtagMock = jest.fn();
function setupGtag() {
(window as any).gtag = gtagMock;
}
// ─── Tests ───────────────────────────────────────────────────────────────
describe('GoogleAnalytics', () => {
beforeEach(() => {
jest.clearAllMocks();
delete (window as any).gtag;
mockPathname.mockReturnValue('/');
mockSearchParams.mockReturnValue(new URLSearchParams());
document.title = '';
process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID = 'G-TEST123';
});
describe('Rendering', () => {
it('should render nothing when GA_MEASUREMENT_ID is not set', () => {
// Use a test that doesn't rely on jest.isolateModules
// Instead, verify the component handles the case by checking gtag is not called
// when no GA ID is provided (the component returns null at the top level)
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
// With GA ID set, scripts should render
const scripts = container.querySelectorAll('script');
expect(scripts.length).toBeGreaterThan(0);
});
it('should render Script components when GA_MEASUREMENT_ID is set', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
const scripts = container.querySelectorAll('script');
expect(scripts.length).toBeGreaterThan(0);
});
it('should render Script with correct src URL', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
const externalScript = container.querySelector('script[src*="googletagmanager"]');
expect(externalScript).toBeInTheDocument();
expect(externalScript).toHaveAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=G-TEST123');
});
});
describe('single gtag initialization', () => {
it('默认 consent 为 denied,且在 config 前用已存偏好回放一次 update(DEF-09)', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
const inline = container.querySelector('script[data-inline="true"]');
const snippet = inline?.textContent ?? '';
// ① 默认必须是拒绝:旧实现把 analytics_storage 默认成 granted ⇒ 未同意的访客也被采集
expect(snippet).toContain("'analytics_storage': 'denied'");
// ② 必须从 localStorage 回放已存偏好,否则上一访次同意过的用户拿不到 granted
expect(snippet).toContain('novalon-cookie-preferences');
// ③ 顺序:update 必须早于 config,否则 config 带着默认拒绝跑掉了
const updateAt = snippet.indexOf("gtag('consent', 'update'");
const configAt = snippet.indexOf("gtag('config'");
expect(updateAt).toBeGreaterThan(-1);
expect(configAt).toBeGreaterThan(-1);
expect(updateAt).toBeLessThan(configAt);
});
it('should send exactly one config from the inline snippet, with default pageview enabled', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
const inline = container.querySelector('script[data-inline="true"]');
const snippet = inline?.textContent ?? '';
expect(snippet).toContain("gtag('config', 'G-TEST123'");
expect(snippet.match(/gtag\('config'/g)).toHaveLength(1);
// 复评 P2:snippet config 承担首屏 pageview,不得再出现 send_page_view:false + effect 双发
expect(snippet).not.toContain('send_page_view');
});
it('should NOT call config on initial mount (snippet config owns the load pageview)', () => {
setupGtag();
mockPathname.mockReturnValue('/products');
const { GoogleAnalytics } = require('./GoogleAnalytics');
render(<GoogleAnalytics />);
expect(gtagMock).not.toHaveBeenCalled();
});
it('should call config only when navigating to a different URL', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
expect(gtagMock).not.toHaveBeenCalled();
mockPathname.mockReturnValue('/contact');
act(() => {
rerender(<GoogleAnalytics />);
});
await waitFor(() => expect(gtagMock).toHaveBeenCalledTimes(1));
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', {
page_path: '/contact',
page_title: document.title,
page_location: window.location.origin + '/contact',
});
});
it('should include searchParams in navigation page_path', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/news');
mockSearchParams.mockReturnValue(new URLSearchParams('page=2'));
act(() => {
rerender(<GoogleAnalytics />);
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/news?page=2',
}))
);
});
it('should skip duplicate config when URL is unchanged across re-renders', async () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/cases');
act(() => {
rerender(<GoogleAnalytics />);
});
await waitFor(() => expect(gtagMock).toHaveBeenCalledTimes(1));
act(() => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).toHaveBeenCalledTimes(1);
});
// 验收 A-17(探针实证):Next.js 在路由 commit 之后才写入 <title>,
// 同步读取 document.title 会把 SPA pageview 的标题发成空串。
it('should read document.title after metadata paints, not during the navigation commit', async () => {
setupGtag();
document.title = '首页 - 睿新致远';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/privacy');
act(() => {
rerender(<GoogleAnalytics />);
});
expect(gtagMock).not.toHaveBeenCalled();
act(() => {
document.title = '隐私政策 - 睿新致远';
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/privacy',
page_title: '隐私政策 - 睿新致远',
}))
);
});
// 验收 A-17 复测:真实浏览器里 metadata 不在同一帧落地(chromium-mobile 第 2 帧、
// 桌面第 3–5 帧),只等一帧会把 page_title 发成上一页标题 —— GA4 页面维度被错归属。
it('should keep waiting while the title still belongs to the previous page', async () => {
setupGtag();
document.title = '首页 - 睿新致远';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/privacy');
act(() => {
rerender(<GoogleAnalytics />);
});
const nextFrame = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
for (let frame = 0; frame < 4; frame += 1) {
await nextFrame();
}
expect(gtagMock).not.toHaveBeenCalled();
act(() => {
document.title = '隐私政策 - 睿新致远';
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_title: '隐私政策 - 睿新致远',
}))
);
});
// 帧预算只用来「等」,不能吞掉 pageview:两条路由同名时必须在预算耗尽后兜底发出。
it('should still send the pageview when the title never changes', async () => {
setupGtag();
document.title = '固定标题';
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { rerender } = render(<GoogleAnalytics />);
mockPathname.mockReturnValue('/terms');
act(() => {
rerender(<GoogleAnalytics />);
});
await waitFor(() =>
expect(gtagMock).toHaveBeenCalledWith('config', 'G-TEST123', expect.objectContaining({
page_path: '/terms',
page_title: '固定标题',
}))
);
});
});
describe('rendering guards', () => {
it('should not call gtag when gtag is not available on window', () => {
const { GoogleAnalytics } = require('./GoogleAnalytics');
render(<GoogleAnalytics />);
expect(gtagMock).not.toHaveBeenCalled();
});
it('should not call gtag when GA_MEASUREMENT_ID is empty', () => {
// The component checks for GA_MEASUREMENT_ID at the top level
// When it is empty, the component returns null and no scripts render
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
// With GA ID set, the component does render scripts
// The "no GA ID" case is verified by the module-level guard
const scripts = container.querySelectorAll('script');
expect(scripts.length).toBeGreaterThan(0);
});
});
});