From a7f49d15c61c98e37a2f7225c378afac7be54c19 Mon Sep 17 00:00:00 2001 From: anushree Date: Fri, 4 Oct 2024 20:37:41 +0530 Subject: [PATCH] Add test for hook useFirstInteractionInternal --- .../hooks/useFirstInteractionInternal.test.ts | 72 +++++++++++++++++++ src/context/BotStatesContext.tsx | 2 +- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 __tests__/hooks/useFirstInteractionInternal.test.ts diff --git a/__tests__/hooks/useFirstInteractionInternal.test.ts b/__tests__/hooks/useFirstInteractionInternal.test.ts new file mode 100644 index 00000000..cd5daedc --- /dev/null +++ b/__tests__/hooks/useFirstInteractionInternal.test.ts @@ -0,0 +1,72 @@ +import { renderHook, act } from '@testing-library/react'; +import { useFirstInteractionInternal } from '../../src/hooks/internal/useFirstInteractionInternal'; + +jest.mock('../../src/context/BotStatesContext', () => ({ + useBotStatesContext: jest.fn(() => ({ + hasInteractedPage: false, + setHasInteractedPage: jest.fn(), + hasFlowStarted: false, + setHasFlowStarted: jest.fn(), + })), +})); + +jest.mock('../../src/context/SettingsContext', () => ({ + useSettingsContext: jest.fn(() => ({ + settings: { + general: { + flowStartTrigger: 'ON_PAGE_INTERACT', + }, + }, + })), +})); +class MockSpeechSynthesisUtterance { + text = ''; + onend: () => void = () => {}; + + constructor() { + setTimeout(() => { + this.onend(); + }, 0); + } + } + + const MockSpeechSynthesis = { + speak: jest.fn().mockImplementation((utterance: MockSpeechSynthesisUtterance) => { + utterance.onend(); + }), + }; + + global.SpeechSynthesisUtterance = MockSpeechSynthesisUtterance as any; + global.speechSynthesis = MockSpeechSynthesis as any; + +describe('useFirstInteractionInternal', () => { + let setHasInteractedPage: jest.Mock; + let setHasFlowStarted: jest.Mock; + + beforeEach(() => { + setHasInteractedPage = jest.fn(); + setHasFlowStarted = jest.fn(); + + (require('../../src/context/BotStatesContext').useBotStatesContext as jest.Mock).mockReturnValue({ + hasInteractedPage: false, + setHasInteractedPage, + hasFlowStarted: false, + setHasFlowStarted, + }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should call setHasInteractedPage and setHasFlowStarted on interaction', () => { + const { result } = renderHook(() => useFirstInteractionInternal()); + + act(() => { + result.current.handleFirstInteraction(); + }); + + expect(setHasInteractedPage).toHaveBeenCalledWith(true); + expect(setHasFlowStarted).toHaveBeenCalledWith(true); + }); +}); diff --git a/src/context/BotStatesContext.tsx b/src/context/BotStatesContext.tsx index 0c67eb28..d875b9e6 100644 --- a/src/context/BotStatesContext.tsx +++ b/src/context/BotStatesContext.tsx @@ -5,7 +5,7 @@ import { Settings } from "../types/Settings"; /** * Creates the useBotStatesContext() hook to manage common states. */ -type BotStatesContextType = { +export type BotStatesContextType = { isBotTyping: boolean; setIsBotTyping: Dispatch>;