Writing Tests for Theme Reducer
Show how to write unit tests for the theme reducer to validate its functionality when handling different actions related to theme switching.
import { toggleTheme } from '../features/themeSlice';
import reducer from '../features/themeSlice';
// Tests for the theme reducer
describe('themeReducer', () => {
// Test initial state
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual({ mode: 'lightMode' });
});
// Test light mode toggle
it('should handle a theme being toggled to light', () => {
const previousState = { mode: 'darkMode' };
expect(reducer(previousState, toggleTheme('lightMode'))).toEqual({ mode: 'lightMode' });
});
// Test dark mode toggle
it('should handle a theme being toggled to dark', () => {
const previousState = { mode: 'lightMode' };
expect(reducer(previousState, toggleTheme('darkMode'))).toEqual({ mode: 'darkMode' });
});
});
This code sets up unit tests for a theme reducer using Jest. It includes tests for checking the initial state and for the functionality of toggling themes between light and dark modes. The 'toggleTheme' action creator is assumed to be defined in the themeSlice feature file.