Skip to main content

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:

  1. A state is initializes using useState hook. The initial value is set to value retrieved from local storage. The value is displayed in a p tag.
  2. The value in the local storage and in the state can be changed when pressing a button. The button calls changeValue function.

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:

  1. mockLocalStorage function is registered to be called in beforeAll function to register a mocked localStorage instance before all tests start.
  2. unmockLocalStorage function is registered to be called in afterAll function to restore original localStorage instance after all tests are finished.
  3. In the it-block:
    1. An item is set in the local storage. This value is accessed in the component.
    2. TestComponent component is rendered.
    3. Check is done to see if the value from local storage is used in the state.
    4. Button is pressed to change local storage and state.
    5. Check is done to see if the value was changed in the local storage and is used in the state.