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, })) const setupHTML = (html: string) => { const div = document.createElement('div') div.innerHTML = html document.querySelector('body')?.appendChild(div) } describe('FormTracking HTML+HubSpot Plugins used together', () => { 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() document.documentElement.innerHTML = '
' }) it('should call identify and track on form submission', async () => { setupHTML(` `) await analytics.register( ddFormTracking({ identifyFromEmail: false, html: {}, hubspot: {}, }) ) // Trigger HTML form submission const form = document.querySelector('form') form?.dispatchEvent(new Event('submit')) // Trigger mocked HubSpot submission const event = new MessageEvent('message', { data: { id: 'test-form', 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-submit')) }) })