import cookie from 'js-cookie' import { waitFor } from '@testing-library/dom' import { Analytics } from '../../../core/analytics' import { ddFormTracking } from '..' import { SegmentioSettings } from '../../segmentio' describe('FormTracking Plugin', () => { let analytics: Analytics let settings: SegmentioSettings let identifySpy: jest.SpyInstance beforeEach(() => { jest.resetAllMocks() jest.restoreAllMocks() global.crypto = { subtle: { // @ts-expect-error // Mock to simulate digest digest: (_, bytes) => Promise.resolve(bytes), }, } settings = { apiKey: 'foo' } analytics = new Analytics({ writeKey: settings.apiKey }) identifySpy = jest.spyOn(analytics, 'identify') }) afterEach(() => { // @ts-expect-error // Reset `crypto` after tests global.crypto = undefined analytics.reset() Object.keys(cookie.get()).map((k) => cookie.remove(k)) window.localStorage.clear() }) it('should load without throwing', async () => { await analytics.register( ddFormTracking({ identifyFromEmail: false, html: {}, }) ) }) it('should not identify from email if id is present', async () => { await analytics.identify('my-id', { email: 'john.doe@example.com' }) await analytics.register( ddFormTracking({ identifyFromEmail: true, html: {}, shouldHash: true, }) ) expect(identifySpy).toHaveBeenCalledTimes(1) }) it('should identify from email if id is missing', async () => { await analytics.identify(null, { email: 'john.doe@example.com' }) await analytics.register( ddFormTracking({ identifyFromEmail: true, html: {}, shouldHash: true, }) ) await waitFor(() => expect(identifySpy).toHaveBeenCalledTimes(2)) expect(identifySpy.mock.calls[1][0]).toBe( '6a6f686e2e646f65406578616d706c652e636f6d' ) }) it('should not identify from email if already done before ', async () => { localStorage.setItem( 'dd_has_identified', analytics.user().anonymousId() as string ) analytics.user().traits({ email: 'john.doe@example.com' }) await analytics.register( ddFormTracking({ identifyFromEmail: true, html: {}, shouldHash: true, }) ) await waitFor(() => expect(identifySpy).toHaveBeenCalledTimes(0)) }) })