From 62f89830e6a9f5184f3fd206473f3335d8f17cbd Mon Sep 17 00:00:00 2001 From: Mallik Cheripally Date: Thu, 8 Aug 2024 16:57:51 +0530 Subject: [PATCH] test: add tests for FocusContext Introduce comprehensive test cases for FocusContext including focus setting, clearing, and context usage. Ensure correct behavior of focus manipulation and expected errors when used outside FocusProvider. --- tests/context/FocusContext.test.tsx | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 tests/context/FocusContext.test.tsx diff --git a/tests/context/FocusContext.test.tsx b/tests/context/FocusContext.test.tsx new file mode 100644 index 0000000..926d2ac --- /dev/null +++ b/tests/context/FocusContext.test.tsx @@ -0,0 +1,65 @@ +import React, { useRef } from 'react'; +import { render, fireEvent, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; + +import { FocusProvider, useFocusContext } from '@/context/FocusContext'; + +const TestComponent: React.FC = () => { + const { focusedElement, setFocusedElement, focusElement } = useFocusContext(); + const inputRef1 = useRef(null); + const inputRef2 = useRef(null); + + return ( +
+ + + + + + {focusedElement ? focusedElement.tagName : 'None'} +
+ ); +}; + +describe('FocusContext', () => { + it('provides context values to children', () => { + render( + + + , + ); + + const input1 = screen.getByTestId('test-input-1') as HTMLInputElement; + const input2 = screen.getByTestId('test-input-2') as HTMLInputElement; + const focusButton1 = screen.getByText('Focus Input 1'); + const focusButton2 = screen.getByText('Focus Input 2'); + const focusedElementDisplay = screen.getByTestId('focused-element'); + + expect(focusedElementDisplay).toHaveTextContent('None'); + + fireEvent.click(focusButton1); + expect(document.activeElement).toBe(input1); + expect(focusedElementDisplay).toHaveTextContent('INPUT'); + + const blurSpy = jest.spyOn(input1, 'blur'); + + fireEvent.click(focusButton2); + expect(document.activeElement).toBe(input2); + expect(focusedElementDisplay).toHaveTextContent('INPUT'); + expect(blurSpy).toHaveBeenCalled(); + + fireEvent.click(screen.getByText('Clear Focus')); + expect(focusedElementDisplay).toHaveTextContent('None'); + }); + + it('throws an error if useFocusContext is used outside of FocusProvider', () => { + const renderWithoutProvider = () => + render( +
+ +
, + ); + + expect(renderWithoutProvider).toThrow('useFocusContext must be used within a FocusProvider'); + }); +});