debian-mirror-gitlab/spec/frontend/__helpers__/local_storage_helper.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

48 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-09-04 21:01:54 +05:30
/**
* Manage the instance of a custom `window.localStorage`
*
* This only encapsulates the setup / teardown logic so that it can easily be
2021-11-11 11:23:49 +05:30
* reused with different implementations (i.e. a spy or a fake)
2019-09-04 21:01:54 +05:30
*
* @param {() => any} fn Function that returns the object to use for localStorage
*/
2021-03-08 18:12:59 +05:30
const useLocalStorage = (fn) => {
2019-09-04 21:01:54 +05:30
const origLocalStorage = window.localStorage;
2020-11-24 15:15:51 +05:30
let currentLocalStorage = origLocalStorage;
2019-09-04 21:01:54 +05:30
Object.defineProperty(window, 'localStorage', {
get: () => currentLocalStorage,
});
beforeEach(() => {
currentLocalStorage = fn();
});
afterEach(() => {
currentLocalStorage = origLocalStorage;
});
};
/**
* Create an object with the localStorage interface but `jest.fn()` implementations.
*/
2020-06-23 00:09:42 +05:30
export const createLocalStorageSpy = () => {
let storage = {};
return {
clear: jest.fn(() => {
storage = {};
}),
2021-03-08 18:12:59 +05:30
getItem: jest.fn((key) => (key in storage ? storage[key] : null)),
2020-06-23 00:09:42 +05:30
setItem: jest.fn((key, value) => {
storage[key] = value;
}),
2021-03-08 18:12:59 +05:30
removeItem: jest.fn((key) => delete storage[key]),
2020-06-23 00:09:42 +05:30
};
};
2019-09-04 21:01:54 +05:30
/**
* Before each test, overwrite `window.localStorage` with a spy implementation.
*/
export const useLocalStorageSpy = () => useLocalStorage(createLocalStorageSpy);