|
| 1 | +import React from 'react'; |
| 2 | +import * as faker from 'faker'; |
| 3 | + |
| 4 | +import * as contextModule from '../../src/contexts/useAnalyticsContext'; |
| 5 | +import {useAnalyticsPageView} from '../../src/hooks/useAnalyticsPageView'; |
| 6 | + |
| 7 | +describe('useAnalyticsPageView', () => { |
| 8 | + const setUp = () => { |
| 9 | + const params = {value: faker.lorem.word()}; |
| 10 | + const callback = () => params; |
| 11 | + const asyncCallback = async () => params; |
| 12 | + |
| 13 | + const onPageView = jest.fn(); |
| 14 | + |
| 15 | + const useEffectSpy = jest.spyOn(React, 'useEffect').mockImplementationOnce(cb => cb()); |
| 16 | + const useContextSpy = jest.spyOn(contextModule, 'useAnalyticsContext').mockImplementationOnce( |
| 17 | + () => |
| 18 | + ({ |
| 19 | + onPageView, |
| 20 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 21 | + } as any), |
| 22 | + ); |
| 23 | + jest.spyOn(console, 'info').mockImplementation(() => null); |
| 24 | + |
| 25 | + return { |
| 26 | + params, |
| 27 | + callback, |
| 28 | + asyncCallback, |
| 29 | + onPageView, |
| 30 | + useEffectSpy, |
| 31 | + useContextSpy, |
| 32 | + }; |
| 33 | + }; |
| 34 | + |
| 35 | + const waitForAsync = () => new Promise(resolve => setTimeout(resolve, 0)); |
| 36 | + |
| 37 | + test('should call analytics.onPageView with params', async () => { |
| 38 | + const {params, onPageView, useContextSpy, useEffectSpy} = setUp(); |
| 39 | + |
| 40 | + useAnalyticsPageView(params); |
| 41 | + await waitForAsync(); |
| 42 | + |
| 43 | + expect(useContextSpy).toHaveBeenCalled(); |
| 44 | + expect(useEffectSpy).toHaveBeenCalled(); |
| 45 | + expect(onPageView).toHaveBeenCalledWith(params); |
| 46 | + }); |
| 47 | + |
| 48 | + test('should call analytics.onPageView with callback', async () => { |
| 49 | + const {params, callback, onPageView, useContextSpy, useEffectSpy} = setUp(); |
| 50 | + |
| 51 | + useAnalyticsPageView(callback); |
| 52 | + await waitForAsync(); |
| 53 | + |
| 54 | + expect(useContextSpy).toHaveBeenCalled(); |
| 55 | + expect(useEffectSpy).toHaveBeenCalled(); |
| 56 | + expect(onPageView).toHaveBeenCalledWith(params); |
| 57 | + }); |
| 58 | + |
| 59 | + test('should call analytics.onPageView with asyncCallback', async () => { |
| 60 | + const {params, asyncCallback, onPageView, useContextSpy, useEffectSpy} = setUp(); |
| 61 | + |
| 62 | + useAnalyticsPageView(asyncCallback); |
| 63 | + await waitForAsync(); |
| 64 | + |
| 65 | + expect(useContextSpy).toHaveBeenCalled(); |
| 66 | + expect(useEffectSpy).toHaveBeenCalled(); |
| 67 | + expect(onPageView).toHaveBeenCalledWith(params); |
| 68 | + }); |
| 69 | +}); |
0 commit comments