|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import { PageViewTracker } from '../../src/trackers/PageViewTracker'; |
| 5 | + |
| 6 | +Object.defineProperty(window, 'location', { |
| 7 | + value: { origin: 'http://localhost:3000', pathname: '/test' }, |
| 8 | +}); |
| 9 | +Object.defineProperty(window, 'sessionStorage', { |
| 10 | + value: { getItem: jest.fn(), setItem: jest.fn(), removeItem: jest.fn() }, |
| 11 | +}); |
| 12 | + |
| 13 | +describe('PageViewTracker', () => { |
| 14 | + let mockEventRecorder: jest.Mock; |
| 15 | + |
| 16 | + beforeEach(() => { |
| 17 | + mockEventRecorder = jest.fn(); |
| 18 | + jest.clearAllMocks(); |
| 19 | + }); |
| 20 | + |
| 21 | + it('should use custom urlProvider when provided', () => { |
| 22 | + const customUrlProvider = jest.fn(() => 'http://localhost:3000/custom'); |
| 23 | + (window.sessionStorage.getItem as jest.Mock).mockReturnValue(null); |
| 24 | + |
| 25 | + const tracker = new PageViewTracker(mockEventRecorder, { |
| 26 | + appType: 'multiPage', |
| 27 | + urlProvider: customUrlProvider, |
| 28 | + }); |
| 29 | + |
| 30 | + expect(customUrlProvider).toHaveBeenCalled(); |
| 31 | + expect(mockEventRecorder).toHaveBeenCalledWith('pageView', { |
| 32 | + url: 'http://localhost:3000/custom', |
| 33 | + }); |
| 34 | + |
| 35 | + tracker.cleanup(); |
| 36 | + }); |
| 37 | + |
| 38 | + it('should use default urlProvider when none provided', () => { |
| 39 | + (window.sessionStorage.getItem as jest.Mock).mockReturnValue(null); |
| 40 | + |
| 41 | + const tracker = new PageViewTracker(mockEventRecorder, { |
| 42 | + appType: 'multiPage', |
| 43 | + }); |
| 44 | + |
| 45 | + expect(mockEventRecorder).toHaveBeenCalledWith('pageView', { |
| 46 | + url: 'http://localhost:3000/test', |
| 47 | + }); |
| 48 | + |
| 49 | + tracker.cleanup(); |
| 50 | + }); |
| 51 | + |
| 52 | + it('should preserve custom urlProvider after reconfiguration', () => { |
| 53 | + const customUrlProvider = jest.fn(() => 'http://localhost:3000/custom'); |
| 54 | + (window.sessionStorage.getItem as jest.Mock).mockReturnValue(null); |
| 55 | + |
| 56 | + const tracker = new PageViewTracker(mockEventRecorder, { |
| 57 | + urlProvider: customUrlProvider, |
| 58 | + }); |
| 59 | + |
| 60 | + tracker.configure(mockEventRecorder, { |
| 61 | + urlProvider: customUrlProvider, |
| 62 | + appType: 'multiPage', |
| 63 | + }); |
| 64 | + |
| 65 | + expect(customUrlProvider).toHaveBeenCalled(); |
| 66 | + expect(mockEventRecorder).toHaveBeenCalledWith('pageView', { |
| 67 | + url: 'http://localhost:3000/custom', |
| 68 | + }); |
| 69 | + |
| 70 | + tracker.cleanup(); |
| 71 | + }); |
| 72 | +}); |
0 commit comments