|
| 1 | +import { ConsentManager } from './consent'; |
| 2 | + |
| 3 | +// Mock fetch for server sync |
| 4 | +const mockFetch = jest.fn().mockResolvedValue({ ok: true, json: async () => ({}) }); |
| 5 | +global.fetch = mockFetch; |
| 6 | + |
| 7 | +beforeEach(() => { |
| 8 | + jest.clearAllMocks(); |
| 9 | +}); |
| 10 | + |
| 11 | +describe('ConsentManager', () => { |
| 12 | + it('initialises with the provided consent level', () => { |
| 13 | + const manager = new ConsentManager('sandbox', 'pk_test', 'anonymous', 'TestSDK'); |
| 14 | + expect(manager.getLevel()).toBe('anonymous'); |
| 15 | + }); |
| 16 | + |
| 17 | + it('calls onPurgeQueue when downgrading to none', () => { |
| 18 | + const manager = new ConsentManager('sandbox', 'pk_test', 'full', 'TestSDK'); |
| 19 | + const onPurge = jest.fn(); |
| 20 | + const onClear = jest.fn(); |
| 21 | + |
| 22 | + manager.setLevel('none', 'anon-123', { |
| 23 | + onPurgeQueue: onPurge, |
| 24 | + onClearCookies: onClear, |
| 25 | + }); |
| 26 | + |
| 27 | + expect(onPurge).toHaveBeenCalled(); |
| 28 | + expect(onClear).toHaveBeenCalled(); |
| 29 | + expect(manager.getLevel()).toBe('none'); |
| 30 | + }); |
| 31 | + |
| 32 | + it('calls onStripIdentity when downgrading from full to anonymous', () => { |
| 33 | + const manager = new ConsentManager('sandbox', 'pk_test', 'full', 'TestSDK'); |
| 34 | + const onStrip = jest.fn(); |
| 35 | + |
| 36 | + manager.setLevel('anonymous', 'anon-123', { onStripIdentity: onStrip }); |
| 37 | + |
| 38 | + expect(onStrip).toHaveBeenCalled(); |
| 39 | + expect(manager.getLevel()).toBe('anonymous'); |
| 40 | + }); |
| 41 | + |
| 42 | + it('syncs consent to server via PUT on setLevel', () => { |
| 43 | + const manager = new ConsentManager('sandbox', 'pk_test', 'none', 'TestSDK'); |
| 44 | + manager.setLevel('full', 'anon-123'); |
| 45 | + |
| 46 | + expect(mockFetch).toHaveBeenCalledWith( |
| 47 | + 'https://api.sandbox.immutable.com/v1/audience/tracking-consent', |
| 48 | + expect.objectContaining({ |
| 49 | + method: 'PUT', |
| 50 | + body: JSON.stringify({ |
| 51 | + anonymousId: 'anon-123', |
| 52 | + status: 'full', |
| 53 | + source: 'TestSDK', |
| 54 | + }), |
| 55 | + }), |
| 56 | + ); |
| 57 | + }); |
| 58 | + |
| 59 | + it('fetches server consent status', async () => { |
| 60 | + mockFetch.mockResolvedValueOnce({ |
| 61 | + ok: true, |
| 62 | + json: async () => ({ status: 'anonymous' }), |
| 63 | + }); |
| 64 | + |
| 65 | + const manager = new ConsentManager('sandbox', 'pk_test', 'none', 'TestSDK'); |
| 66 | + const status = await manager.fetchServerConsent('anon-123'); |
| 67 | + |
| 68 | + expect(status).toBe('anonymous'); |
| 69 | + expect(mockFetch).toHaveBeenCalledWith( |
| 70 | + 'https://api.sandbox.immutable.com/v1/audience/tracking-consent?anonymousId=anon-123', |
| 71 | + expect.objectContaining({ |
| 72 | + headers: { 'x-immutable-publishable-key': 'pk_test' }, |
| 73 | + }), |
| 74 | + ); |
| 75 | + }); |
| 76 | +}); |
0 commit comments