To test the behavior of the Search component in regard to local storage — specifically, ensuring that the search value is saved to local storage when the search button is clicked and that the component retrieves the value from local storage upon mounting — we can follow the steps below.
- Set up the testing environment, making sure to mock local storage.
- Write tests that simulate user actions and verify the expected behavior.
Here are the steps detailed:
-
Install Dependencies: Ensure you have the required testing packages installed. If not, run:
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom jsdom
-
Simulate Local Storage in Tests: You can use jest.Mock to simulate local storage.
-
Create Tests: Write tests in a new test file SearchSectionLocalStorage.test.tsx.
Here's the entire SearchSectionLocalStorage.test.tsx file to test the behavior you described:
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { BrowserRouter } from 'react-router-dom';
import SearchSection from './SearchSection'; // Adjust import path
describe('SearchSection component local storage behavior', () => {
const mockParentStateItems = jest.fn();
const mockParentStateIsLoaded = jest.fn();
beforeEach(() => {
mockParentStateItems.mockClear();
mockParentStateIsLoaded.mockClear();
// Clear and mock local storage
localStorage.clear();
jest.spyOn(Storage.prototype, 'setItem');
jest.spyOn(Storage.prototype, 'getItem');
});
test('saves the search query to local storage when search button is clicked', async () => {
render(
<BrowserRouter>
<SearchSection
parentStateItems={mockParentStateItems}
parentStateIsLoaded={mockParentStateIsLoaded}
/>
</BrowserRouter>
);
const searchInput = screen.getByPlaceholderText('Search by name...');
fireEvent.change(searchInput, { target: { value: 'Yoda' } });
const searchButton = screen.getByText('Search');
fireEvent.click(searchButton);
await waitFor(() => {
expect(localStorage.setItem).toHaveBeenCalledWith('query', 'Yoda');
});
});
test('retrieves the search query from local storage upon mounting', () => {
// Set a value in local storage before rendering the component
localStorage.setItem('query', 'Leia');
render(
<BrowserRouter>
<SearchSection
parentStateItems={mockParentStateItems}
parentStateIsLoaded={mockParentStateIsLoaded}
/>
</BrowserRouter>
);
// Verify that the input value is set correctly from local storage
expect(screen.getByPlaceholderText('Search by name...')).toHaveValue('Leia');
});
});
Explanation
-
Mocks:
- We mock local storage methods (
setItem and getItem) to observe their calls and behaviors.
- Before each test, we clear the mocks and local storage to prevent state leakage between tests.
-
Tests:
- Save to Local Storage:
- Simulate a user typing in the search input and clicking the "Search" button.
- Verify that
localStorage.setItem is called with the expected arguments.
- Retrieve from Local Storage:
- Set a predefined value in local storage.
- Render the component and verify that it correctly reads from local storage and sets the input value accordingly.
Implementation Note
For handling the initial state on component mount based on local storage, you need to ensure your hook or state initialization logic in SearchSection is correctly set up. If using a custom useSearchQuery hook, ensure it reads the initial state as follows:
import { useState, useEffect } from 'react';
// Custom hook to manage search query with local storage
function useSearchQuery(key: string) {
const [value, setValue] = useState<string>(() => localStorage.getItem(key) || '');
useEffect(() => {
localStorage.setItem(key, value);
}, [key, value]);
return [value, setValue] as const;
}
Ensure your SearchSection uses this custom hook and initial state setup accordingly. Adjust the paths and method names according to your existing implementation.