import React from 'react'; import { QuizleSidebar, QuizleSideBarProps } from '../QuizleSidebar'; import { render, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; import { useTrackingContext } from '../../../helpers/tracking/TrackingContextProvider'; jest.mock('../../../helpers/tracking/TrackingContextProvider', () => ({ useTrackingContext: jest.fn() })); const mockFireAnalyticsEvent = jest.fn(); const defaultProps: QuizleSideBarProps = { sectionTitle: 'Puzzles for you', pageLink: 'https://www.thetimes.com/puzzles', quizleQuestion: "Which type of dog gets its name from the Welsh words for 'dwarf' and 'dog'?" }; const renderComponent = (props: QuizleSideBarProps) => render(); describe('QuizleSidebar', () => { beforeEach(() => { jest.clearAllMocks(); (useTrackingContext as jest.Mock).mockReturnValue({ fireAnalyticsEvent: mockFireAnalyticsEvent }); }); afterEach(() => { jest.clearAllMocks(); }); it('should render QuizleSidebar component', () => { const { asFragment } = renderComponent(defaultProps); expect(asFragment()).toMatchSnapshot(); }); it('should call fireAnalyticsEvent when header is clicked', () => { const { container } = renderComponent(defaultProps); fireEvent.click(container.querySelector('.trigger')!); expect(mockFireAnalyticsEvent).toHaveBeenCalledWith({ object: 'QuizleSidebar', action: 'Clicked', attrs: { event_navigation_action: 'navigation', event_navigation_name: 'quizle sidebar: title selected', event_navigation_browsing_method: 'click', component_name: 'Quizle Sidebar' } }); }); it('should call fireAnalyticsEvent when a puzzle card is clicked', () => { const { container } = renderComponent(defaultProps); fireEvent.click(container.querySelector('.quizle-link')!); expect(mockFireAnalyticsEvent).toHaveBeenCalledWith({ object: 'QuizleSidebar', action: 'Clicked', attrs: { event_navigation_action: 'navigation', event_navigation_name: 'quizle sidebar: test your knowledge', event_navigation_browsing_method: 'click', component_name: 'Quizle Sidebar' } }); }); it('should display the question from quizleQuestion prop', () => { const { getByText } = renderComponent(defaultProps); expect( getByText( "Which type of dog gets its name from the Welsh words for 'dwarf' and 'dog'?" ) ).toBeInTheDocument(); }); it('should display a custom question when provided', () => { const customProps = { ...defaultProps, quizleQuestion: 'What is the capital of France?' }; const { getByText } = renderComponent(customProps); expect(getByText('What is the capital of France?')).toBeInTheDocument(); }); it('should handle null quizleQuestion gracefully', () => { const propsWithoutQuestion = { sectionTitle: 'Puzzles for you', pageLink: 'https://www.thetimes.com/puzzles' }; const { container } = renderComponent(propsWithoutQuestion); // Component should still render without crashing expect( container.querySelector('[data-testid="quizleSidebar"]') ).toBeInTheDocument(); }); });