import cookie from 'js-cookie' import { waitFor } from '@testing-library/dom' import { Analytics } from '../../../core/analytics' import { ddFormTracking } from '..' import { SegmentioSettings } from '../../segmentio' // It is not possible to mock `isTrusted` property of the // event, hence we move it to a util file that can be mocked jest.mock('../utils', () => ({ ...jest.requireActual('../utils'), eventIsTrusted: () => true, })) describe('FormTracking Hubspot Plugin', () => { let analytics: Analytics let settings: SegmentioSettings let identifySpy: jest.SpyInstance let trackSpy: jest.SpyInstance beforeEach(() => { jest.resetAllMocks() jest.restoreAllMocks() settings = { apiKey: 'foo' } analytics = new Analytics({ writeKey: settings.apiKey }) identifySpy = jest.spyOn(analytics, 'identify') trackSpy = jest.spyOn(analytics, 'track') }) afterEach(() => { analytics.reset() Object.keys(cookie.get()).map((k) => cookie.remove(k)) window.localStorage.clear() }) it('should call identify and track on message', async () => { await analytics.register( ddFormTracking({ identifyFromEmail: false, hubspot: {}, }) ) const event = new MessageEvent('message', { data: { data: [{ name: 'email', value: 'my-value' }], type: 'hsFormCallback', eventName: 'onFormSubmit', }, }) window.dispatchEvent(event) await waitFor(() => expect(identifySpy).toHaveBeenCalledTimes(1)) await waitFor(() => expect(trackSpy).toHaveBeenCalledTimes(1)) await waitFor(() => expect(trackSpy.mock.calls[0][0]).toBe('form-hubspot-submit') ) }) })