refactor unit test

This commit is contained in:
Simone Taeggi 2023-02-03 18:05:12 +01:00
parent f3ee8e94fe
commit 2c0fa4897a
8 changed files with 2281 additions and 123 deletions

View File

@ -1,13 +0,0 @@
import { transformPermissionsData } from './utils';
const init = (state, permissions = []) => {
return {
...state,
selectedAction: null,
routes: [],
selectedActions: [],
data: transformPermissionsData(permissions),
};
};
export default init;

View File

@ -1,72 +0,0 @@
/* eslint-disable consistent-return */
import produce from 'immer';
import { pull } from 'lodash';
import { transformPermissionsData } from './utils';
export const initialState = {
data: {},
selectedActions: [],
};
const reducer = (state, action) =>
produce(state, (draftState) => {
switch (action.type) {
case 'ON_CHANGE': {
if (draftState.selectedActions.includes(action.value)) {
pull(draftState.selectedActions, action.value);
} else {
draftState.selectedActions.push(action.value);
}
break;
}
case 'SELECT_ALL_IN_PERMISSION': {
const areAllSelected = action.value.every((item) =>
draftState.selectedActions.includes(item.actionId)
);
if (areAllSelected) {
action.value.forEach((item) => {
pull(draftState.selectedActions, item.actionId);
});
} else {
action.value.forEach((item) => {
draftState.selectedActions.push(item.actionId);
});
}
break;
}
case 'SELECT_ALL_ACTIONS': {
draftState.selectedActions = [...draftState.data.allActionsIds];
break;
}
case 'ON_CHANGE_READ_ONLY': {
const onlyReadOnlyActions = draftState.data.allActionsIds.filter(
(actionId) => actionId.includes('find') || actionId.includes('findOne')
);
draftState.selectedActions = [...onlyReadOnlyActions];
break;
}
case 'UPDATE_PERMISSIONS_LAYOUT': {
draftState.data = transformPermissionsData(action.value);
break;
}
case 'UPDATE_ROUTES': {
draftState.routes = { ...action.value };
break;
}
case 'UPDATE_PERMISSIONS': {
draftState.selectedActions = [...action.value];
break;
}
case 'SET_SELECTED_ACTION': {
draftState.selectedAction = action.value;
break;
}
default:
return draftState;
}
});
export default reducer;

View File

@ -0,0 +1,114 @@
import React from 'react';
import { render, waitFor } from '@testing-library/react';
import { IntlProvider } from 'react-intl';
import { Router, Route } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { QueryClient, QueryClientProvider } from 'react-query';
import { lightTheme, darkTheme } from '@strapi/design-system';
import Theme from '../../../../../../components/Theme';
import ThemeToggleProvider from '../../../../../../components/ThemeToggleProvider';
import EditView from '../index';
import { data } from '../utils/tests/dataMock';
jest.mock('@strapi/helper-plugin', () => ({
...jest.requireActual('@strapi/helper-plugin'),
useNotification: jest.fn(),
useFocusWhenNavigate: jest.fn(),
useTracking: jest.fn(() => ({ trackUsage: jest.fn() })),
useRBAC: jest.fn(() => ({
allowedActions: {
canCreate: true,
canDelete: true,
canRead: true,
canUpdate: true,
canRegenerate: true,
},
})),
useGuidedTour: jest.fn(() => ({
startSection: jest.fn(),
})),
useOverlayBlocker: jest.fn(() => ({
lockApp: jest.fn(),
unlockApp: jest.fn(),
})),
useFetchClient: jest.fn().mockReturnValue({
get: jest.fn().mockImplementation((path) => {
if (path === '/admin/content-api/permissions') {
return { data };
}
return {
data: {
data: {
id: '1',
name: 'My super token',
description: 'This describe my super token',
type: 'read-only',
createdAt: '2021-11-15T00:00:00.000Z',
permissions: [],
},
},
};
}),
}),
}));
jest.spyOn(Date, 'now').mockImplementation(() => new Date('2015-10-01T08:00:00.000Z'));
const client = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
const makeApp = (history) => {
return (
<QueryClientProvider client={client}>
<IntlProvider messages={{}} defaultLocale="en" textComponent="span" locale="en">
<ThemeToggleProvider themes={{ light: lightTheme, dark: darkTheme }}>
<Theme>
<Router history={history}>
<Route path="/settings/transfer-tokens/:id">
<EditView />
</Route>
</Router>
</Theme>
</ThemeToggleProvider>
</IntlProvider>
</QueryClientProvider>
);
};
describe('ADMIN | Pages | TRANSFER TOKENS | EditView', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('renders and matches the snapshot when creating token', async () => {
const history = createMemoryHistory();
const App = makeApp(history);
const { container } = render(App);
history.push('/settings/transfer-tokens/create');
expect(container).toMatchSnapshot();
});
it('renders and matches the snapshot when editing existing token', async () => {
const history = createMemoryHistory();
const App = makeApp(history);
const { container, getByText } = render(App);
history.push('/settings/transfer-tokens/1');
await waitFor(() => {
expect(getByText('My super token')).toBeInTheDocument();
expect(getByText('This describe my super token')).toBeInTheDocument();
expect(getByText('Regenerate')).toBeInTheDocument();
});
expect(container).toMatchSnapshot();
});
});

View File

@ -1,5 +1,4 @@
import getDateOfExpiration from './getDateOfExpiration';
import schema from './schema';
import transformPermissionsData from './transformPermissionsData';
export { getDateOfExpiration, schema, transformPermissionsData };
export { getDateOfExpiration, schema };

View File

@ -0,0 +1,14 @@
export const data = {
data: {
'api::address': {
controllers: {
address: ['find', 'findOne'],
},
},
'api::category': {
controllers: {
category: ['find', 'findOne', 'create', 'update', 'delete', 'createLocalization'],
},
},
},
};

View File

@ -0,0 +1,14 @@
import getDateOfExpiration from '../getDateOfExpiration';
const createdAt = '2022-07-05T12:16:56.821Z';
const duration = 604800000;
describe('ADMIN | Pages | TRANSFER TOKENS | EditView', () => {
it('should return a formated date of expiration', () => {
expect(getDateOfExpiration(createdAt, duration)).toBe('July 12th, 2022');
});
it('should return a formated date in french', () => {
expect(getDateOfExpiration(createdAt, duration, 'fr')).toBe('12 juillet 2022');
});
});

View File

@ -1,36 +0,0 @@
import { flatten } from 'lodash';
const transformPermissionsData = (data) => {
const layout = {
allActionsIds: [],
permissions: [],
};
layout.permissions = Object.keys(data).map((apiId) => ({
apiId,
label: apiId.split('::')[1],
controllers: flatten(
Object.keys(data[apiId].controllers).map((controller) => ({
controller,
actions: flatten(
data[apiId].controllers[controller].map((action) => {
const actionId = `${apiId}.${controller}.${action}`;
if (apiId.includes('api::')) {
layout.allActionsIds.push(actionId);
}
return {
action,
actionId,
};
})
),
}))
),
}));
return layout;
};
export default transformPermissionsData;