prometheus

Форк
0
/
useLocalStorage.test.tsx 
41 строка · 1.6 Кб
1
import { useLocalStorage } from './useLocalStorage';
2
import { renderHook, act } from '@testing-library/react-hooks';
3

4
describe('useLocalStorage', () => {
5
  it('returns the initialState', () => {
6
    const initialState = { a: 1, b: 2 };
7
    const { result } = renderHook(() => useLocalStorage('mystorage', initialState));
8
    expect(result.current[0]).toEqual(initialState);
9
  });
10
  it('stores the initialState as serialized json in localstorage', () => {
11
    const key = 'mystorage';
12
    const initialState = { a: 1, b: 2 };
13
    renderHook(() => useLocalStorage(key, initialState));
14
    expect(localStorage.getItem(key)).toEqual(JSON.stringify(initialState));
15
  });
16
  it('returns a setValue function that can reset local storage', () => {
17
    const key = 'mystorage';
18
    const initialState = { a: 1, b: 2 };
19
    const { result } = renderHook(() => useLocalStorage(key, initialState));
20
    const newValue = { a: 2, b: 5 };
21
    act(() => {
22
      result.current[1](newValue);
23
    });
24
    expect(result.current[0]).toEqual(newValue);
25
    expect(localStorage.getItem(key)).toEqual(JSON.stringify(newValue));
26
  });
27
  it('localStorage.getItem calls once', () => {
28
    // do not prepare the initial state on every render except the first
29
    const spyStorage = jest.spyOn(Storage.prototype, 'getItem') as jest.Mock;
30

31
    const key = 'mystorage';
32
    const initialState = { a: 1, b: 2 };
33
    const { result } = renderHook(() => useLocalStorage(key, initialState));
34
    const newValue = { a: 2, b: 5 };
35
    act(() => {
36
      result.current[1](newValue);
37
    });
38
    expect(spyStorage).toHaveBeenCalledTimes(1);
39
    spyStorage.mockReset();
40
  });
41
});
42

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.