Skip to content

Commit

Permalink
provide various missing unit tests (#1474)
Browse files Browse the repository at this point in the history
Provide tests for hideEmail, loginServices, okapiActions, okapiReducer,
and processBadResponse.

Tiny refactor of some loginServices functions to:
* consistently test for success, else handle an error
* consistently test for success in responses by checking `response.ok`
  rather than `response.status`. consistency is nice. it's predictable.
  • Loading branch information
zburke authored Jun 17, 2024
1 parent e93a5af commit ac49090
Show file tree
Hide file tree
Showing 6 changed files with 513 additions and 22 deletions.
8 changes: 8 additions & 0 deletions src/helpers/hideEmail/hideEmail.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import hideEmail from './hideEmail';

describe('hideEmail', () => {
it('masks email addresses', () => {
expect(hideEmail('[email protected]')).toEqual('te**@e******.***');
expect(hideEmail('[email protected]')).toEqual('mo****@b****.*****');
});
});
21 changes: 11 additions & 10 deletions src/loginServices.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ function dispatchLocale(url, store, tenant) {
mode: 'cors',
})
.then((response) => {
if (response.status === 200) {
if (response.ok) {
response.json().then((json) => {
if (json.configs?.length) {
const localeValues = JSON.parse(json.configs[0].value);
Expand All @@ -237,6 +237,7 @@ function dispatchLocale(url, store, tenant) {
}
});
}

return response;
});
}
Expand Down Expand Up @@ -303,7 +304,7 @@ export function getPlugins(okapiUrl, store, tenant) {
mode: 'cors',
})
.then((response) => {
if (response.status < 400) {
if (response.ok) {
response.json().then((json) => {
const configs = json.configs?.reduce((acc, val) => ({
...acc,
Expand Down Expand Up @@ -333,9 +334,7 @@ export function getBindings(okapiUrl, store, tenant) {
})
.then((response) => {
let bindings = {};
if (response.status >= 400) {
store.dispatch(setBindings(bindings));
} else {
if (response.ok) {
response.json().then((json) => {
const configs = json.configs;
if (Array.isArray(configs) && configs.length > 0) {
Expand All @@ -350,6 +349,8 @@ export function getBindings(okapiUrl, store, tenant) {
}
store.dispatch(setBindings(bindings));
});
} else {
store.dispatch(setBindings(bindings));
}
return response;
});
Expand Down Expand Up @@ -578,14 +579,14 @@ export function createOkapiSession(okapiUrl, store, tenant, token, data) {
export function getSSOEnabled(okapiUrl, store, tenant) {
return fetch(`${okapiUrl}/saml/check`, { headers: { 'X-Okapi-Tenant': tenant, 'Accept': 'application/json' } })
.then((response) => {
if (response.status >= 400) {
store.dispatch(checkSSO(false));
return null;
} else {
if (response.ok) {
return response.json()
.then((json) => {
store.dispatch(checkSSO(json.active));
});
} else {
store.dispatch(checkSSO(false));
return null;
}
})
.catch(() => {
Expand All @@ -601,7 +602,7 @@ export function getSSOEnabled(okapiUrl, store, tenant) {
* @param {object} resp fetch Response
*/
function processSSOLoginResponse(resp) {
if (resp.status < 400) {
if (resp.ok) {
resp.json().then((json) => {
const form = document.getElementById('ssoForm');
if (json.bindingMethod === 'POST') {
Expand Down
79 changes: 75 additions & 4 deletions src/loginServices.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ import localforage from 'localforage';

import {
createOkapiSession,
getBindings,
getLocale,
getPlugins,
getOkapiSession,
getTokenExpiry,
getUserLocale,
handleLoginError,
loadTranslations,
logout,
Expand All @@ -24,10 +28,10 @@ import {
clearOkapiToken,
setCurrentPerms,
setLocale,
// setTimezone,
// setCurrency,
// setPlugins,
// setBindings,
setTimezone,
setCurrency,
setPlugins,
setBindings,
// setTranslations,
setAuthError,
// checkSSO,
Expand All @@ -53,6 +57,7 @@ const mockFetchSuccess = (data) => {
global.fetch = jest.fn().mockImplementation(() => (
Promise.resolve({
ok: true,
status: 200,
json: () => Promise.resolve(data),
headers: new Map(),
})
Expand Down Expand Up @@ -541,3 +546,69 @@ describe('logout', () => {
});
});
});

describe('getLocale', () => {
it('dispatches setTimezone, setCurrency', async () => {
const value = { timezone: 'America/New_York', currency: 'USD' };
mockFetchSuccess({ configs: [{ value: JSON.stringify(value) }] });
const store = {
dispatch: jest.fn(),
getState: () => ({ okapi: { } }),
};
await getLocale('url', store, 'tenant');
expect(store.dispatch).toHaveBeenCalledWith(setTimezone(value.timezone));
expect(store.dispatch).toHaveBeenCalledWith(setCurrency(value.currency));
mockFetchCleanUp();
});
});

describe('getUserLocale', () => {
it('dispatches setTimezone, setCurrency', async () => {
const value = { locale: 'en-US', timezone: 'America/New_York', currency: 'USD' };
mockFetchSuccess({ configs: [{ value: JSON.stringify(value) }] });
const store = {
dispatch: jest.fn(),
getState: () => ({ okapi: { } }),
};
await getUserLocale('url', store, 'tenant');
expect(store.dispatch).toHaveBeenCalledWith(setTimezone(value.timezone));
expect(store.dispatch).toHaveBeenCalledWith(setCurrency(value.currency));
mockFetchCleanUp();
});
});

describe('getPlugins', () => {
it('dispatches setPlugins', async () => {
const configs = [
{ configName: 'find-user', value: '@folio/plugin-hello-waldo' },
{ configName: 'find-water', value: '@folio/plugin-dowsing-rod' },
];
mockFetchSuccess({ configs });
const store = {
dispatch: jest.fn(),
getState: () => ({ okapi: { } }),
};
await getPlugins('url', store, 'tenant');

const mappedConfigs = configs.reduce((acc, val) => ({
...acc,
[val.configName]: val.value,
}), {});
expect(store.dispatch).toHaveBeenCalledWith(setPlugins(mappedConfigs));
mockFetchCleanUp();
});
});

describe('getBindings', () => {
it('dispatches setBindings', async () => {
const value = { key: 'value' };
mockFetchSuccess({ configs: [{ value: JSON.stringify(value) }] });
const store = {
dispatch: jest.fn(),
getState: () => ({ okapi: { } }),
};
await getBindings('url', store, 'tenant');
expect(store.dispatch).toHaveBeenCalledWith(setBindings(value));
mockFetchCleanUp();
});
});
150 changes: 150 additions & 0 deletions src/okapiActions.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,85 @@
import {
checkSSO,
clearCurrentUser,
clearOkapiToken,
clearRtrTimeout,
setAuthError,
setBindings,
setCurrency,
setCurrentPerms,
setCurrentUser,
setIsAuthenticated,
setLocale,
setLoginData,
setOkapiReady,
setOkapiToken,
setPlugins,
setRtrTimeout,
setServerDown,
setSessionData,
setSinglePlugin,
setTimezone,
setTokenExpiration,
setTranslations,
toggleRtrModal,
updateCurrentUser,
} from './okapiActions';


describe('checkSSO', () => {
it('sets ssoEnabled', () => {
expect(checkSSO('monkey').ssoEnabled).toBe('monkey');
});
});

describe('clearCurrentUser', () => {
it('returns an action with a type', () => {
expect(clearCurrentUser()).toHaveProperty('type');
});
});

describe('clearOkapiToken', () => {
it('returns an action with a type', () => {
expect(clearOkapiToken()).toHaveProperty('type');
});
});

describe('clearRtrTimeout', () => {
it('returns an action with a type', () => {
expect(clearRtrTimeout()).toHaveProperty('type');
});
});

describe('setAuthError', () => {
it('sets message', () => {
expect(setAuthError('message').message).toBe('message');
});
});

describe('setBindings', () => {
it('sets bindings', () => {
expect(setBindings('bindings').bindings).toBe('bindings');
});
});

describe('setCurrency', () => {
it('sets currency', () => {
expect(setCurrency('currency').currency).toBe('currency');
});
});

describe('setCurrentPerms', () => {
it('sets currentPerms', () => {
expect(setCurrentPerms('currentPerms').currentPerms).toBe('currentPerms');
});
});

describe('setCurrentUser', () => {
it('sets currentUser', () => {
expect(setCurrentUser('currentUser').currentUser).toBe('currentUser');
});
});

describe('setIsAuthenticated', () => {
it('handles truthy values', () => {
expect(setIsAuthenticated('truthy').isAuthenticated).toBe(true);
Expand All @@ -18,13 +94,87 @@ describe('setIsAuthenticated', () => {
});
});

describe('setLocale', () => {
it('sets locale', () => {
expect(setLocale('locale').locale).toBe('locale');
});
});

describe('setLoginData', () => {
it('receives given data in "loginData"', () => {
const av = { monkey: 'bagel' };
expect(setLoginData(av).loginData).toMatchObject(av);
});
});

describe('setOkapiReady', () => {
it('returns an action with a type', () => {
expect(setOkapiReady()).toHaveProperty('type');
});
});

describe('setOkapiToken', () => {
it('sets token', () => {
expect(setOkapiToken('token').token).toBe('token');
});
});

describe('setPlugins', () => {
it('sets plugins', () => {
expect(setPlugins('plugins').plugins).toBe('plugins');
});
});

describe('setRtrTimeout', () => {
it('sets rtrTimeout', () => {
expect(setRtrTimeout('rtrTimeout').rtrTimeout).toBe('rtrTimeout');
});
});

describe('setServerDown', () => {
it('returns an action with a type', () => {
expect(setServerDown()).toHaveProperty('type');
});
});

describe('setSessionData', () => {
it('sets session', () => {
expect(setSessionData('session').session).toBe('session');
});
});

describe('setSinglePlugin', () => {
it('sets name and value', () => {
const ret = setSinglePlugin('name', 'value');
expect(ret.name).toBe('name');
expect(ret.value).toBe('value');
});
});

describe('setTimezone', () => {
it('sets timezone', () => {
expect(setTimezone('timezone').timezone).toBe('timezone');
});
});

describe('setTokenExpiration', () => {
it('sets tokenExpiration', () => {
expect(setTokenExpiration('tokenExpiration').tokenExpiration).toBe('tokenExpiration');
});
});

describe('setTranslations', () => {
it('sets translations', () => {
expect(setTranslations('translations').translations).toBe('translations');
});
});

describe('toggleRtrModal', () => {
it('sets isVisible', () => {
expect(toggleRtrModal(true).isVisible).toBe(true);
});
});

describe('updateCurrentUser', () => {
it('receives given data in "data"', () => {
const av = { monkey: 'bagel' };
Expand Down
Loading

0 comments on commit ac49090

Please sign in to comment.