import { isCrawler, addMonthToDate, getEventObject, httpRequest } from './helpers' const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' const _Date = Date const mockDate = () => { const MOCKED_DATE = new Date(2017, 10, 21, 23, 10, 20) ;(global as any).Date = jest.fn(() => MOCKED_DATE) } const resetDate = () => { ;(global as any).Date = _Date } describe('Helper', () => { describe('isCrawler', () => { it('Should not be flagged as a crawler', () => { expect(isCrawler(userAgent)).toBe(false) }) it('Should be flagged as a crawler', () => { expect(isCrawler('googlebot user agent')).toBe(true) }) it('Should be flagged as a crawler (case insensitive', () => { expect(isCrawler('GOOGLEBOT user agent')).toBe(true) }) }) describe('addMonthToDate', () => { beforeEach(mockDate) it('Should render the date', () => { expect( addMonthToDate(0) .toString() .startsWith('Tue Nov 21 2017 23:10:20') ).toBe(true) }) it('Should render the date with 1 more month', () => { expect( addMonthToDate(1) .toString() .startsWith('Thu Dec 21 2017 23:10:20') ).toBe(true) }) it('Should render the date with 2 more month and a change of year', () => { expect( addMonthToDate(2) .toString() .startsWith('Sun Jan 21 2018 23:10:20') ).toBe(true) }) afterEach(resetDate) }) describe('getEventObject', () => { beforeEach(mockDate) it('Should render a Tracktor event', () => { expect(getEventObject('name', 1, {})).toEqual({ name: 'name', version: 1, payload: {}, created_at_client_local: '2017-11-21T23:10:20+01:00', }) }) afterEach(resetDate) }) describe('httpRequest', () => { const url = 'url' const opts = { body: { parameter: 'value' } } global.fetch = jest.fn().mockImplementation(() => Promise.resolve({ ok: true })) beforeEach(() => { navigator.sendBeacon = undefined }) it('Should use sendBeacon if this is available', () => { navigator.sendBeacon = jest.fn() httpRequest(url, opts) expect(navigator.sendBeacon).toHaveBeenCalledWith(url, opts.body) }) it('Should use fetch if sendBeacon is not available', () => { httpRequest(url, opts) expect(global.fetch).toHaveBeenCalled() }) }) })