|
| 1 | +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; |
| 2 | +import { ThemeToggle } from './themeToggle'; |
| 3 | +import { useTheme } from 'next-themes'; |
| 4 | + |
| 5 | +jest.mock('next-themes', () => ({ |
| 6 | + useTheme: jest.fn(), |
| 7 | +})); |
| 8 | + |
| 9 | +afterEach(cleanup); |
| 10 | + |
| 11 | +describe('ThemeToggle', () => { |
| 12 | + it('should render Sun and Moon icons', () => { |
| 13 | + (useTheme as jest.Mock).mockReturnValue({ |
| 14 | + theme: 'dark', |
| 15 | + setTheme: jest.fn(), |
| 16 | + }); |
| 17 | + render(<ThemeToggle />); |
| 18 | + |
| 19 | + const moonIcon = screen.getByTestId('moon-icon'); |
| 20 | + const sunIcon = screen.getByTestId('sun-icon'); |
| 21 | + expect(moonIcon).toBeInTheDocument(); |
| 22 | + expect(sunIcon).toBeInTheDocument(); |
| 23 | + }); |
| 24 | + |
| 25 | + it('should toggle light theme on button click', () => { |
| 26 | + const setThemeMock = jest.fn(); |
| 27 | + (useTheme as jest.Mock).mockReturnValue({ |
| 28 | + theme: 'light', |
| 29 | + setTheme: setThemeMock, |
| 30 | + }); |
| 31 | + render(<ThemeToggle />); |
| 32 | + const toggleButton = screen.getByRole('button', { name: 'Toggle theme' }); |
| 33 | + fireEvent.click(toggleButton); |
| 34 | + expect(setThemeMock).toHaveBeenCalledWith('dark'); |
| 35 | + }); |
| 36 | + |
| 37 | + it('should toggle dark theme on button click', () => { |
| 38 | + const setThemeMock = jest.fn(); |
| 39 | + (useTheme as jest.Mock).mockReturnValue({ |
| 40 | + theme: 'dark', |
| 41 | + setTheme: setThemeMock, |
| 42 | + }); |
| 43 | + render(<ThemeToggle />); |
| 44 | + const toggleButton = screen.getByRole('button', { name: 'Toggle theme' }); |
| 45 | + fireEvent.click(toggleButton); |
| 46 | + expect(setThemeMock).toHaveBeenCalledWith('light'); |
| 47 | + }); |
| 48 | +}); |
0 commit comments