Addresses some object mutation issues and improves testing

This commit is contained in:
Alex Corey
2020-04-23 11:35:58 -04:00
parent 4c72ab896a
commit df1489bcee
4 changed files with 194 additions and 103 deletions

View File

@@ -85,7 +85,6 @@ function InventorySourceList({ i18n }) {
await handleDeleteSources(); await handleDeleteSources();
setSelected([]); setSelected([]);
}; };
const canAdd = const canAdd =
sourceChoicesOptions && sourceChoicesOptions &&
Object.prototype.hasOwnProperty.call(sourceChoicesOptions, 'POST'); Object.prototype.hasOwnProperty.call(sourceChoicesOptions, 'POST');
@@ -97,7 +96,7 @@ function InventorySourceList({ i18n }) {
hasContentLoading={isLoading || isDeleteLoading} hasContentLoading={isLoading || isDeleteLoading}
items={sources} items={sources}
itemCount={sourceCount} itemCount={sourceCount}
pluralizedItemName={i18n._(t`Sources`)} pluralizedItemName={i18n._(t`Inventory Sources`)}
qsConfig={QS_CONFIG} qsConfig={QS_CONFIG}
renderToolbar={props => ( renderToolbar={props => (
<DatalistToolbar <DatalistToolbar
@@ -116,15 +115,16 @@ function InventorySourceList({ i18n }) {
key="delete" key="delete"
onDelete={handleDelete} onDelete={handleDelete}
itemsToDelete={selected} itemsToDelete={selected}
pluralizedItemName={i18n._(t`Inventory Source`)} pluralizedItemName={i18n._(t`Inventory Sources`)}
/>, />,
]} ]}
/> />
)} )}
renderItem={inventorySource => { renderItem={inventorySource => {
let label;
sourceChoices.forEach(([scMatch, scLabel]) => { sourceChoices.forEach(([scMatch, scLabel]) => {
if (inventorySource.source === scMatch) { if (inventorySource.source === scMatch) {
inventorySource.source = scLabel; label = scLabel;
} }
}); });
return ( return (
@@ -132,6 +132,7 @@ function InventorySourceList({ i18n }) {
key={inventorySource.id} key={inventorySource.id}
source={inventorySource} source={inventorySource}
onSelect={() => handleSelect(inventorySource)} onSelect={() => handleSelect(inventorySource)}
label={label}
detailUrl={`${detailUrl}${inventorySource.id}`} detailUrl={`${detailUrl}${inventorySource.id}`}
isSelected={selected.some(row => row.id === inventorySource.id)} isSelected={selected.some(row => row.id === inventorySource.id)}
/> />
@@ -140,6 +141,7 @@ function InventorySourceList({ i18n }) {
/> />
{deletionError && ( {deletionError && (
<AlertModal <AlertModal
aria-label={i18n._(t`Delete Error`)}
isOpen={deletionError} isOpen={deletionError}
variant="error" variant="error"
title={i18n._(t`Error!`)} title={i18n._(t`Error!`)}

View File

@@ -68,6 +68,7 @@ describe('<InventorySourceList />', () => {
}); });
}); });
afterEach(() => { afterEach(() => {
wrapper.unmount();
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('should mount properly', async () => { test('should mount properly', async () => {
@@ -123,6 +124,97 @@ describe('<InventorySourceList />', () => {
); );
expect(InventorySourcesAPI.destroy).toHaveBeenCalledWith(1); expect(InventorySourcesAPI.destroy).toHaveBeenCalledWith(1);
}); });
test('should throw error after deletion failure', async () => {
InventorySourcesAPI.destroy.mockRejectedValue(
new Error({
response: {
config: {
method: 'delete',
url: '/api/v2/inventory_sources/',
},
data: 'An error occurred',
status: 403,
},
})
);
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
await act(async () =>
wrapper.find('DataListCheck').prop('onChange')({ id: 1 })
);
wrapper.update();
await act(async () =>
wrapper.find('Button[aria-label="Delete"]').prop('onClick')()
);
wrapper.update();
await act(async () =>
wrapper.find('Button[aria-label="confirm delete"]').prop('onClick')()
);
wrapper.update();
expect(wrapper.find("AlertModal[aria-label='Delete Error']").length).toBe(
1
);
});
test('displays error after unseccessful read sources fetch', async () => {
InventorySourcesAPI.readOptions.mockRejectedValue(
new Error({
response: {
config: {
method: 'get',
url: '/api/v2/inventories/inventory_sources/',
},
data: 'An error occurred',
status: 403,
},
})
);
InventoriesAPI.readSources.mockRejectedValue(
new Error({
response: {
config: {
method: 'get',
url: '/api/v2/inventories/inventory_sources/',
},
data: 'An error occurred',
status: 403,
},
})
);
await act(async () => {
wrapper = mountWithContexts(<InventorySourceList />);
});
await waitForElement(wrapper, 'ContentError', el => el.length > 0);
expect(wrapper.find('ContentError').length).toBe(1);
});
test('displays error after unseccessful read options fetch', async () => {
InventorySourcesAPI.readOptions.mockRejectedValue(
new Error({
response: {
config: {
method: 'options',
url: '/api/v2/inventory_sources/',
},
data: 'An error occurred',
status: 403,
},
})
);
await act(async () => {
wrapper = mountWithContexts(<InventorySourceList />);
});
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0);
expect(wrapper.find('ContentError').length).toBe(1);
});
}); });
describe('<InventorySourceList /> RBAC testing', () => { describe('<InventorySourceList /> RBAC testing', () => {
@@ -156,12 +248,12 @@ describe('<InventorySourceList /> RBAC testing', () => {
}, },
}, },
}); });
let wrapper; let newWrapper;
const history = createMemoryHistory({ const history = createMemoryHistory({
initialEntries: ['/inventories/inventory/1/sources'], initialEntries: ['/inventories/inventory/2/sources'],
}); });
await act(async () => { await act(async () => {
wrapper = mountWithContexts( newWrapper = mountWithContexts(
<Route path="/inventories/:inventoryType/:id/sources"> <Route path="/inventories/:inventoryType/:id/sources">
<InventorySourceList /> <InventorySourceList />
</Route>, </Route>,
@@ -171,15 +263,20 @@ describe('<InventorySourceList /> RBAC testing', () => {
history, history,
route: { route: {
location: { search: '' }, location: { search: '' },
match: { params: { id: 1 } }, match: { params: { id: 2 } },
}, },
}, },
}, },
} }
); );
}); });
await waitForElement(
await waitForElement(wrapper, 'InventorySourceList', el => el.length > 0); newWrapper,
expect(wrapper.find('ToolbarAddButton').length).toBe(0); 'InventorySourceList',
el => el.length > 0
);
expect(newWrapper.find('ToolbarAddButton').length).toBe(0);
newWrapper.unmount();
jest.clearAllMocks();
}); });
}); });

View File

@@ -1,4 +1,4 @@
import React from 'react'; import React from 'react';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
@@ -19,51 +19,49 @@ function InventorySourceListItem({
onSelect, onSelect,
i18n, i18n,
detailUrl, detailUrl,
label,
}) { }) {
return ( return (
<> <DataListItem aria-labelledby={`check-action-${source.id}`}>
<DataListItem aria-labelledby={`check-action-${source.id}`}> <DataListItemRow>
<DataListItemRow> <DataListCheck
<DataListCheck id={`select-source-${source.id}`}
id={`select-source-${source.id}`} checked={isSelected}
checked={isSelected} onChange={onSelect}
onChange={onSelect} aria-labelledby={`check-action-${source.id}`}
aria-labelledby={`check-action-${source.id}`} />
/> <DataListItemCells
<DataListItemCells dataListCells={[
dataListCells={[ <DataListCell aria-label={i18n._(t`name`)} key="name">
<DataListCell aria-label={i18n._(t`name`)} key="name"> <span>
<span> <Link to={`${detailUrl}/details`}>
<Link to={`${detailUrl}/details`}> <b>{source.name}</b>
<b>{source.name}</b> </Link>
</Link> </span>
</span> </DataListCell>,
</DataListCell>, <DataListCell aria-label={i18n._(t`type`)} key="type">
<DataListCell aria-label={i18n._(t`type`)} key="type"> {label}
{source.source} </DataListCell>,
</DataListCell>, ]}
]} />
/> <DataListAction
<DataListAction id="actions"
id="actions" aria-labelledby="actions"
aria-labelledby="actions" aria-label="actions"
aria-label="actions" >
> {source.summary_fields.user_capabilities.edit && (
{source.summary_fields.user_capabilities.edit && ( <Button
<Button aria-label={i18n._(t`Edit Source`)}
aria-label={i18n._(t`Edit Source`)} variant="plain"
variant="plain" component={Link}
component={Link} to={`${detailUrl}/edit`}
to={`${detailUrl}/edit`} >
> <PencilAltIcon />
<PencilAltIcon /> </Button>
</Button> )}
)} </DataListAction>
</DataListAction> </DataListItemRow>
</DataListItemRow> </DataListItem>
</DataListItem>
</>
); );
} }
export default withI18n()(InventorySourceListItem); export default withI18n()(InventorySourceListItem);

View File

@@ -1,5 +1,4 @@
import React from 'react'; import React from 'react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '@testUtils/enzymeHelpers'; import { mountWithContexts } from '@testUtils/enzymeHelpers';
import InventorySourceListItem from './InventorySourceListItem'; import InventorySourceListItem from './InventorySourceListItem';
@@ -10,35 +9,34 @@ const source = {
summary_fields: { user_capabilities: { start: true, edit: true } }, summary_fields: { user_capabilities: { start: true, edit: true } },
}; };
describe('<InventorySourceListItem />', () => { describe('<InventorySourceListItem />', () => {
let wrapper;
afterEach(() => { afterEach(() => {
wrapper.unmount();
jest.clearAllMocks(); jest.clearAllMocks();
}); });
test('should mount properly', async () => { test('should mount properly', () => {
let wrapper;
const onSelect = jest.fn(); const onSelect = jest.fn();
await act(async () => { wrapper = mountWithContexts(
wrapper = mountWithContexts( <InventorySourceListItem
<InventorySourceListItem source={source}
source={source} isSelected={false}
isSelected={false} onSelect={onSelect}
onSelect={onSelect} label="Source Bar"
/> />
); );
});
expect(wrapper.find('InventorySourceListItem').length).toBe(1); expect(wrapper.find('InventorySourceListItem').length).toBe(1);
}); });
test('all buttons and text fields should render properly', async () => {
let wrapper; test('all buttons and text fields should render properly', () => {
const onSelect = jest.fn(); const onSelect = jest.fn();
await act(async () => { wrapper = mountWithContexts(
wrapper = mountWithContexts( <InventorySourceListItem
<InventorySourceListItem source={source}
source={source} isSelected={false}
isSelected={false} onSelect={onSelect}
onSelect={onSelect} label="Source Bar"
/> />
); );
});
expect(wrapper.find('DataListCheck').length).toBe(1); expect(wrapper.find('DataListCheck').length).toBe(1);
expect( expect(
wrapper wrapper
@@ -55,37 +53,33 @@ describe('<InventorySourceListItem />', () => {
expect(wrapper.find('PencilAltIcon').length).toBe(1); expect(wrapper.find('PencilAltIcon').length).toBe(1);
}); });
test('item should be checked', async () => { test('item should be checked', () => {
let wrapper;
const onSelect = jest.fn(); const onSelect = jest.fn();
await act(async () => { wrapper = mountWithContexts(
wrapper = mountWithContexts( <InventorySourceListItem
<InventorySourceListItem source={source}
source={source} isSelected
isSelected onSelect={onSelect}
onSelect={onSelect} label="Source Bar"
/> />
); );
});
expect(wrapper.find('DataListCheck').length).toBe(1); expect(wrapper.find('DataListCheck').length).toBe(1);
expect(wrapper.find('DataListCheck').prop('checked')).toBe(true); expect(wrapper.find('DataListCheck').prop('checked')).toBe(true);
}); });
test(' should render edit buttons', async () => { test(' should render edit buttons', () => {
let wrapper;
const onSelect = jest.fn(); const onSelect = jest.fn();
await act(async () => { wrapper = mountWithContexts(
wrapper = mountWithContexts( <InventorySourceListItem
<InventorySourceListItem source={{
source={{ ...source,
...source, summary_fields: { user_capabilities: { edit: false, start: true } },
summary_fields: { user_capabilities: { edit: false, start: true } }, }}
}} isSelected={false}
isSelected={false} onSelect={onSelect}
onSelect={onSelect} label="Source Bar"
/> />
); );
});
expect(wrapper.find('Button[aria-label="Edit Source"]').length).toBe(0); expect(wrapper.find('Button[aria-label="Edit Source"]').length).toBe(0);
}); });
}); });