move getting of hidden users to utils

* get hidden user by util
* add tests for changed actions
* add tests for getting users from local storage
This commit is contained in:
Pavel Mineev
2020-03-25 01:52:46 -05:00
committed by Umputun
parent e7dfd1efbb
commit 7ce400a5e5
4 changed files with 99 additions and 15 deletions
@@ -0,0 +1,33 @@
import { LS_HIDDEN_USERS_KEY } from '@app/common/constants';
import getHiddenUsers from './get-hidden-users';
describe('getHiddenUsers', () => {
it('should get hidden users from local storage', async () => {
localStorage.setItem(LS_HIDDEN_USERS_KEY, JSON.stringify([]));
expect(getHiddenUsers()).toEqual({});
});
it('should return empty object with array in local storage', async () => {
localStorage.setItem(LS_HIDDEN_USERS_KEY, JSON.stringify([]));
expect(getHiddenUsers()).toEqual({});
});
it('should return empty object with null in local storage', async () => {
localStorage.setItem(LS_HIDDEN_USERS_KEY, JSON.stringify(null));
expect(getHiddenUsers()).toEqual({});
});
it('should return empty object with string in local storage', async () => {
localStorage.setItem(LS_HIDDEN_USERS_KEY, JSON.stringify('string'));
expect(getHiddenUsers()).toEqual({});
});
test('should return empty object and log error with invalid JSON in localStorage', async () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
localStorage.setItem(LS_HIDDEN_USERS_KEY, '"{:"""');
expect(getHiddenUsers()).toEqual({});
expect(consoleSpy).toHaveBeenCalled();
});
});
+17
View File
@@ -0,0 +1,17 @@
import { User } from '@app/common/types';
import { getItem } from '@app/common/local-storage';
import { LS_HIDDEN_USERS_KEY } from '@app/common/constants';
export default function getHiddenUsers() {
try {
const hiddenUsers: Record<string, User> = JSON.parse(getItem(LS_HIDDEN_USERS_KEY) || '{}');
if (typeof hiddenUsers === 'object' && hiddenUsers !== null && !Array.isArray(hiddenUsers)) {
return hiddenUsers;
}
} catch (e) {
console.error('incorrect hidden user data in local storage', e); // eslint-disable-line no-console
}
return {};
}