import { describe, it, expect, beforeEach, jest } from '@jest/globals'; // Set GA ID before importing process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID = 'G-TEST123'; // Mock localStorage const localStorageMock = (() => { let store: Record = {}; return { getItem: jest.fn((key: string) => store[key] ?? null), setItem: jest.fn((key: string, value: string) => { store[key] = value; }), removeItem: jest.fn((key: string) => { delete store[key]; }), clear: jest.fn(() => { store = {}; }), }; })(); Object.defineProperty(window, 'localStorage', { value: localStorageMock, }); describe('Analytics', () => { let analytics: typeof import('./analytics'); beforeEach(async () => { jest.clearAllMocks(); localStorageMock.clear(); // Reset gtag delete (window as any).gtag; analytics = await import('./analytics'); }); describe('getDefaultPreferences', () => { it('should return default preferences', () => { const prefs = analytics.getDefaultPreferences(); expect(prefs.necessary).toBe(true); expect(prefs.analytics).toBe(true); expect(prefs.marketing).toBe(false); expect(prefs.functionality).toBe(true); }); it('should return a copy, not the original', () => { const prefs1 = analytics.getDefaultPreferences(); const prefs2 = analytics.getDefaultPreferences(); expect(prefs1).not.toBe(prefs2); }); }); describe('getStoredPreferences', () => { it('should return null when no preferences stored', () => { const result = analytics.getStoredPreferences(); expect(result).toBeNull(); }); it('should return stored preferences', () => { const testPrefs = { necessary: true, analytics: false, marketing: true, functionality: true }; localStorageMock.setItem('novalon-cookie-preferences', JSON.stringify(testPrefs)); const result = analytics.getStoredPreferences(); expect(result).toEqual(testPrefs); }); it('should return null on malformed JSON', () => { localStorageMock.setItem('novalon-cookie-preferences', 'not-json'); const result = analytics.getStoredPreferences(); expect(result).toBeNull(); }); // Q-10③:localStorage 可能被篡改/写坏;同意判定必须严格,真值非布尔不得当作已同意(fail-closed)。 it('coerces truthy non-boolean consent fields to false instead of granting', () => { localStorageMock.setItem( 'novalon-cookie-preferences', JSON.stringify({ necessary: false, analytics: 'yes', marketing: 1, functionality: true }) ); const result = analytics.getStoredPreferences(); expect(result).toEqual({ necessary: true, // 必要类恒真,不受存储值影响 analytics: false, // 'yes' 非严格 true ⇒ 不授予 marketing: false, // 1 非严格 true ⇒ 不授予 functionality: true, }); }); it('ignores a non-object payload (array/number) rather than trusting it', () => { localStorageMock.setItem('novalon-cookie-preferences', '[1,2,3]'); const result = analytics.getStoredPreferences(); expect(result).toEqual({ necessary: true, analytics: false, marketing: false, functionality: false, }); }); }); describe('storePreferences', () => { it('should store preferences to localStorage', () => { const prefs = { necessary: true, analytics: true, marketing: false, functionality: true }; analytics.storePreferences(prefs); expect(localStorageMock.setItem).toHaveBeenCalledWith( 'novalon-cookie-preferences', JSON.stringify(prefs) ); }); it('should throw and warn on localStorage error', () => { localStorageMock.setItem.mockImplementationOnce(() => { throw new Error('Storage full'); }); // 本地 spy:jest.setup.js 只静音 info/debug,warn 不再是全局 mock const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); analytics.storePreferences({ necessary: true, analytics: true, marketing: false, functionality: true, }); expect(warnSpy).toHaveBeenCalled(); warnSpy.mockRestore(); }); }); describe('updateConsentDetailed', () => { it('should call gtag when available', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.updateConsentDetailed({ necessary: true, analytics: true, marketing: false, functionality: true, }); expect(gtag).toHaveBeenCalledWith('consent', 'update', { analytics_storage: 'granted', ad_storage: 'denied', functionality_storage: 'granted', }); }); it('should not call gtag when not available', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.updateConsentDetailed({ necessary: true, analytics: false, marketing: true, functionality: false, }); expect(gtag).toHaveBeenCalledWith('consent', 'update', { analytics_storage: 'denied', ad_storage: 'granted', functionality_storage: 'denied', }); }); }); describe('trackEvent', () => { it('should call gtag when available', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackEvent('click', 'engagement', 'button-1', 1); expect(gtag).toHaveBeenCalledWith('event', 'click', { event_category: 'engagement', event_label: 'button-1', event_value: 1, send_to: 'G-TEST123', }); }); it('should not call gtag when not available', () => { expect((window as any).gtag).toBeUndefined(); expect(() => analytics.trackEvent('click', 'engagement', 'button-1', 1) ).not.toThrow(); }); }); describe('trackButtonClick', () => { it('should call trackEvent with button name', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackButtonClick('submit-form', 'contact-page'); expect(gtag).toHaveBeenCalledWith('event', 'button_click', { event_category: 'engagement', event_label: 'submit-form', event_value: undefined, send_to: 'G-TEST123', }); }); }); describe('trackError', () => { it('should call gtag with error data when available', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackError('API_ERROR', 'Failed to fetch', true, { statusCode: 500 }); expect(gtag).toHaveBeenCalledWith('event', 'exception', { description: '[API_ERROR] Failed to fetch', fatal: 'true', url: window.location.href, timestamp: expect.any(String), statusCode: 500, send_to: 'G-TEST123', }); }); it('should warn when gtag is not available', () => { const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); analytics.trackError('TEST', 'No gtag'); expect(warnSpy).toHaveBeenCalled(); warnSpy.mockRestore(); }); it('should set fatal to "false" string when not fatal', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackError('WARN', 'Minor issue', false); const callArgs = gtag.mock.calls[0]?.[2] as Record; expect(callArgs?.fatal).toBe('false'); }); it('should not echo tracked errors to the console', () => { const gtag = jest.fn(); (window as any).gtag = gtag; const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); analytics.trackError('API_ERROR', 'Failed to fetch', true); expect(logSpy).not.toHaveBeenCalled(); logSpy.mockRestore(); }); }); describe('trackPageView', () => { it('should call gtag with page data', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackPageView('/products', 'Products'); expect(gtag).toHaveBeenCalledWith('config', 'G-TEST123', { page_path: '/products', page_title: 'Products', }); }); it('should not throw when gtag is not available', () => { expect((window as any).gtag).toBeUndefined(); expect(() => analytics.trackPageView('/', 'Home')).not.toThrow(); }); }); describe('trackPerformance', () => { it('should call gtag with performance data', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackPerformance('LCP', 2500, 'web_vitals'); expect(gtag).toHaveBeenCalledWith('event', 'LCP', { event_category: 'web_vitals', event_value: 2500, value: 2500, send_to: 'G-TEST123', }); }); it('should round value to integer', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackPerformance('FID', 12.7); const callArgs = gtag.mock.calls[0]?.[2] as Record; expect(callArgs?.value).toBe(13); }); it('should use default category', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackPerformance('CLS', 0.1); const callArgs = gtag.mock.calls[0]?.[2] as Record; expect(callArgs?.event_category).toBe('web_vitals'); }); }); describe('trackContactForm', () => { it('should call gtag with form data object', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackContactForm({ name: 'Test', email: 'test@test.com', company: 'TestCorp' }, true); expect(gtag).toHaveBeenCalledWith('event', 'form_submit', { event_category: 'contact', event_label: 'TestCorp', event_value: 1, send_to: 'G-TEST123', }); }); it('should call gtag with string form data', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackContactForm('simple-form', false); expect(gtag).toHaveBeenCalledWith('event', 'form_submit', { event_category: 'contact', event_label: 'simple-form', event_value: 0, send_to: 'G-TEST123', }); }); it('should not track conversion when success is false', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackContactForm('failed-form', false); // Only the form_submit event, not conversion expect(gtag).toHaveBeenCalledTimes(1); }); }); describe('trackConversion', () => { it('should call gtag with conversion data', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackConversion('signup_complete', 5); expect(gtag).toHaveBeenCalledWith('event', 'conversion', { send_to: 'G-TEST123', transaction_id: expect.any(String), value: 5, currency: 'CNY', conversion_label: 'signup_complete', }); }); it('should default value to 1', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackConversion('page_viewed'); const callArgs = gtag.mock.calls[0]?.[2] as Record; expect(callArgs?.value).toBe(1); }); it('should keep an explicit value of 0', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackConversion('zero_value_conversion', 0); const callArgs = gtag.mock.calls[0]?.[2] as Record; expect(callArgs?.value).toBe(0); }); }); describe('trackOutboundLink', () => { it('should send exactly one outbound_click event', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackOutboundLink('https://example.com', 'Example'); // 旧实现同时发 outbound_click 与 click,GA4 里每次外跳被双计。 expect(gtag).toHaveBeenCalledTimes(1); expect(gtag).toHaveBeenCalledWith('event', 'outbound_click', { event_category: 'engagement', event_label: 'https://example.com', event_value: undefined, send_to: 'G-TEST123', }); expect(gtag).not.toHaveBeenCalledWith('event', 'click', expect.anything()); }); }); describe('trackScrollDepth', () => { it('should call trackEvent with scroll percentage', () => { const gtag = jest.fn(); (window as any).gtag = gtag; analytics.trackScrollDepth(50); expect(gtag).toHaveBeenCalledWith('event', 'scroll_50', { event_category: 'engagement', event_label: '50%', event_value: undefined, send_to: 'G-TEST123', }); }); }); });