localStorage
The @archibald/testing package provides a set of functions to work with localStorage object.
import { mockLocalStorage, unmockLocalStorage, resetLocalStorage } from '@archibald/testing';
// Mock global localStorage instance.
mockLocalStorage();
// Reset global localStorage instance to default one.
unmockLocalStorage();
// Reset global localStorage instance.
resetLocalStorage();
Example
Let's have a look at the following example.
const key = 'test-key';
function TestComponent() {
const [value, setValue] = useState(() => {
const localStorageValue = localStorage.getItem(key);
return localStorageValue ? localStorageValue : 'not set';
});
function changeValue() {
localStorage.setItem(key, 'value 2');
const localStorageValue = localStorage.getItem(key);
if (localStorageValue) {
setValue(localStorageValue);
}
}
return (
<>
<p data-testid="value">{value}</p>
<Button testId="button" onClick={changeValue}>
Change value
</Button>
</>
);
}
export default TestComponent;
In this example following is done:
- A state is initializes using
useStatehook. The initial value is set to value retrieved from local storage. The value is displayed in aptag. - The value in the local storage and in the state can be changed when pressing a button. The button calls
changeValuefunction.
A test for this component could look like following:
// Other imports
import { fireEvent, mockLocalStorage, render, unmockLocalStorage } from '@archibald/testing';
const key = 'test-key';
const value1 = 'value 1';
const value2 = 'value 2';
describe('<TestComponent /> component', () => {
beforeAll(() => {
mockLocalStorage();
});
afterAll(() => {
unmockLocalStorage();
});
it('should render', async () => {
localStorage.setItem(key, 'value 1');
const component = render(<TestComponent />);
const pEl = await component.findByTestId('value');
const buttonEl = await component.findByTestId('button');
expect(pEl).toHaveTextContent(value1);
fireEvent.click(buttonEl);
expect(pEl).toHaveTextContent(value2);
});
});
In this test following is done:
mockLocalStoragefunction is registered to be called inbeforeAllfunction to register a mockedlocalStorageinstance before all tests start.unmockLocalStoragefunction is registered to be called inafterAllfunction to restore originallocalStorageinstance after all tests are finished.- In the
it-block:- An item is set in the local storage. This value is accessed in the component.
TestComponentcomponent is rendered.- Check is done to see if the value from local storage is used in the state.
- Button is pressed to change local storage and state.
- Check is done to see if the value was changed in the local storage and is used in the state.