|
| 1 | +import { getOrCreateAnonymousId, getAnonymousId } from './cookie'; |
| 2 | +import { COOKIE_NAME } from './config'; |
| 3 | + |
| 4 | +function clearCookies() { |
| 5 | + document.cookie.split(';').forEach((c) => { |
| 6 | + const name = c.split('=')[0].trim(); |
| 7 | + document.cookie = `${name}=; max-age=0; path=/`; |
| 8 | + }); |
| 9 | +} |
| 10 | + |
| 11 | +beforeEach(clearCookies); |
| 12 | + |
| 13 | +describe('getOrCreateAnonymousId', () => { |
| 14 | + it('generates a new ID when no cookie exists', () => { |
| 15 | + const id = getOrCreateAnonymousId(); |
| 16 | + expect(id).toBeTruthy(); |
| 17 | + expect(typeof id).toBe('string'); |
| 18 | + }); |
| 19 | + |
| 20 | + it('persists the ID in a cookie', () => { |
| 21 | + const id = getOrCreateAnonymousId(); |
| 22 | + expect(document.cookie).toContain(`${COOKIE_NAME}=${id}`); |
| 23 | + }); |
| 24 | + |
| 25 | + it('returns the same ID on subsequent calls', () => { |
| 26 | + const first = getOrCreateAnonymousId(); |
| 27 | + const second = getOrCreateAnonymousId(); |
| 28 | + expect(second).toBe(first); |
| 29 | + }); |
| 30 | + |
| 31 | + it('returns an existing cookie value if already set', () => { |
| 32 | + document.cookie = `${COOKIE_NAME}=existing-id; path=/`; |
| 33 | + expect(getOrCreateAnonymousId()).toBe('existing-id'); |
| 34 | + }); |
| 35 | +}); |
| 36 | + |
| 37 | +describe('getAnonymousId', () => { |
| 38 | + it('returns undefined when no cookie exists', () => { |
| 39 | + expect(getAnonymousId()).toBeUndefined(); |
| 40 | + }); |
| 41 | + |
| 42 | + it('returns the cookie value when set', () => { |
| 43 | + document.cookie = `${COOKIE_NAME}=test-id; path=/`; |
| 44 | + expect(getAnonymousId()).toBe('test-id'); |
| 45 | + }); |
| 46 | +}); |
0 commit comments