summaryrefslogtreecommitdiff
path: root/spec/frontend/__helpers__/local_storage_helper.js
blob: cf75b0b53fe2021754b9bd1a66be3079b6c5748c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Manage the instance of a custom `window.localStorage`
 *
 * This only encapsulates the setup / teardown logic so that it can easily be
 * reused with different implementations (i.e. a spy or a fake)
 *
 * @param {() => any} fn Function that returns the object to use for localStorage
 */
const useLocalStorage = (fn) => {
  const origLocalStorage = window.localStorage;
  let currentLocalStorage = origLocalStorage;

  Object.defineProperty(window, 'localStorage', {
    get: () => currentLocalStorage,
  });

  beforeEach(() => {
    currentLocalStorage = fn();
  });

  afterEach(() => {
    currentLocalStorage = origLocalStorage;
  });
};

/**
 * Create an object with the localStorage interface but `jest.fn()` implementations.
 */
export const createLocalStorageSpy = () => {
  let storage = {};

  return {
    clear: jest.fn(() => {
      storage = {};
    }),
    getItem: jest.fn((key) => (key in storage ? storage[key] : null)),
    setItem: jest.fn((key, value) => {
      storage[key] = value;
    }),
    removeItem: jest.fn((key) => delete storage[key]),
  };
};

/**
 * Before each test, overwrite `window.localStorage` with a spy implementation.
 */
export const useLocalStorageSpy = () => useLocalStorage(createLocalStorageSpy);