1
0
mirror of https://github.com/ansible/awx.git synced 2024-11-01 16:51:11 +03:00

Merge pull request #5517 from jakemcdermott/ui-next-org-functional-components

Move routed organization views to functional components

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot] 2019-12-18 16:15:57 +00:00 committed by GitHub
commit e4c3454b98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 638 additions and 649 deletions

View File

@ -1,6 +1,6 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import {
@ -16,7 +16,8 @@ import { Config } from '@contexts/Config';
import CardCloseButton from '@components/CardCloseButton';
import OrganizationForm from '../shared/OrganizationForm';
function OrganizationAdd({ history, i18n }) {
function OrganizationAdd({ i18n }) {
const history = useHistory();
const [formError, setFormError] = useState(null);
const handleSubmit = async (values, groupsToAssociate) => {
@ -67,4 +68,4 @@ OrganizationAdd.contextTypes = {
};
export { OrganizationAdd as _OrganizationAdd };
export default withI18n()(withRouter(OrganizationAdd));
export default withI18n()(OrganizationAdd);

View File

@ -1,5 +1,5 @@
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { Link, useRouteMatch } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { CardBody as PFCardBody, Button } from '@patternfly/react-core';
@ -16,46 +16,11 @@ const CardBody = styled(PFCardBody)`
padding-top: 20px;
`;
class OrganizationDetail extends Component {
constructor(props) {
super(props);
this.state = {
contentError: null,
hasContentLoading: true,
instanceGroups: [],
};
this.loadInstanceGroups = this.loadInstanceGroups.bind(this);
}
componentDidMount() {
this.loadInstanceGroups();
}
async loadInstanceGroups() {
function OrganizationDetail({ i18n, organization }) {
const {
match: {
params: { id },
},
} = this.props;
this.setState({ hasContentLoading: true });
try {
} = useRouteMatch();
const {
data: { results = [] },
} = await OrganizationsAPI.readInstanceGroups(id);
this.setState({ instanceGroups: [...results] });
} catch (err) {
this.setState({ contentError: err });
} finally {
this.setState({ hasContentLoading: false });
}
}
render() {
const { hasContentLoading, contentError, instanceGroups } = this.state;
const {
organization: {
name,
description,
custom_virtualenv,
@ -63,10 +28,27 @@ class OrganizationDetail extends Component {
created,
modified,
summary_fields,
},
match,
i18n,
} = this.props;
} = organization;
const [contentError, setContentError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(true);
const [instanceGroups, setInstanceGroups] = useState([]);
useEffect(() => {
(async () => {
setContentError(null);
setHasContentLoading(true);
try {
const {
data: { results = [] },
} = await OrganizationsAPI.readInstanceGroups(id);
setInstanceGroups(results);
} catch (error) {
setContentError(error);
} finally {
setHasContentLoading(false);
}
})();
}, [id]);
if (hasContentLoading) {
return <ContentLoading />;
@ -90,10 +72,7 @@ class OrganizationDetail extends Component {
label={i18n._(t`Ansible Environment`)}
value={custom_virtualenv}
/>
<Detail
label={i18n._(t`Created`)}
value={formatDateString(created)}
/>
<Detail label={i18n._(t`Created`)} value={formatDateString(created)} />
<Detail
label={i18n._(t`Last Modified`)}
value={formatDateString(modified)}
@ -116,17 +95,13 @@ class OrganizationDetail extends Component {
</DetailList>
{summary_fields.user_capabilities.edit && (
<div css="margin-top: 10px; text-align: right;">
<Button
component={Link}
to={`/organizations/${match.params.id}/edit`}
>
<Button component={Link} to={`/organizations/${id}/edit`}>
{i18n._(t`Edit`)}
</Button>
</div>
)}
</CardBody>
);
}
}
export default withI18n()(withRouter(OrganizationDetail));
export default withI18n()(OrganizationDetail);

View File

@ -1,4 +1,5 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { OrganizationsAPI } from '@api';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
@ -35,30 +36,42 @@ describe('<OrganizationDetail />', () => {
jest.clearAllMocks();
});
test('initially renders succesfully', () => {
test('initially renders succesfully', async () => {
await act(async () => {
mountWithContexts(<OrganizationDetail organization={mockOrganization} />);
});
});
test('should request instance groups from api', () => {
test('should request instance groups from api', async () => {
await act(async () => {
mountWithContexts(<OrganizationDetail organization={mockOrganization} />);
});
expect(OrganizationsAPI.readInstanceGroups).toHaveBeenCalledTimes(1);
});
test('should handle setting instance groups to state', async done => {
const wrapper = mountWithContexts(
test('should render the expected instance group', async () => {
let component;
await act(async () => {
component = mountWithContexts(
<OrganizationDetail organization={mockOrganization} />
);
const component = await waitForElement(wrapper, 'OrganizationDetail');
expect(component.state().instanceGroups).toEqual(
mockInstanceGroups.data.results
);
done();
});
await waitForElement(component, 'ContentLoading', el => el.length === 0);
expect(
component
.find('Chip')
.findWhere(el => el.text() === 'One')
.exists()
).toBe(true);
});
test('should render Details', async done => {
const wrapper = mountWithContexts(
test('should render Details', async () => {
let wrapper;
await act(async () => {
wrapper = mountWithContexts(
<OrganizationDetail organization={mockOrganization} />
);
});
const testParams = [
{ label: 'Name', value: 'Foo' },
{ label: 'Description', value: 'Bar' },
@ -74,30 +87,34 @@ describe('<OrganizationDetail />', () => {
expect(detail.find('dt').text()).toBe(label);
expect(detail.find('dd').text()).toBe(value);
}
done();
});
test('should show edit button for users with edit permission', async done => {
const wrapper = mountWithContexts(
test('should show edit button for users with edit permission', async () => {
let wrapper;
await act(async () => {
wrapper = mountWithContexts(
<OrganizationDetail organization={mockOrganization} />
);
});
const editButton = await waitForElement(
wrapper,
'OrganizationDetail Button'
);
expect(editButton.text()).toEqual('Edit');
expect(editButton.prop('to')).toBe('/organizations/undefined/edit');
done();
});
test('should hide edit button for users without edit permission', async done => {
test('should hide edit button for users without edit permission', async () => {
const readOnlyOrg = { ...mockOrganization };
readOnlyOrg.summary_fields.user_capabilities.edit = false;
const wrapper = mountWithContexts(
let wrapper;
await act(async () => {
wrapper = mountWithContexts(
<OrganizationDetail organization={readOnlyOrg} />
);
});
await waitForElement(wrapper, 'OrganizationDetail');
expect(wrapper.find('OrganizationDetail Button').length).toBe(0);
done();
});
});

View File

@ -1,6 +1,6 @@
import React, { Component } from 'react';
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import { CardBody } from '@patternfly/react-core';
import { OrganizationsAPI } from '@api';
@ -8,50 +8,18 @@ import { Config } from '@contexts/Config';
import OrganizationForm from '../shared/OrganizationForm';
class OrganizationEdit extends Component {
constructor(props) {
super(props);
function OrganizationEdit({ organization }) {
const detailsUrl = `/organizations/${organization.id}/details`;
const history = useHistory();
const [formError, setFormError] = useState(null);
this.handleSubmit = this.handleSubmit.bind(this);
this.submitInstanceGroups = this.submitInstanceGroups.bind(this);
this.handleCancel = this.handleCancel.bind(this);
this.handleSuccess = this.handleSuccess.bind(this);
this.state = {
error: '',
};
}
async handleSubmit(values, groupsToAssociate, groupsToDisassociate) {
const { organization } = this.props;
const handleSubmit = async (
values,
groupsToAssociate,
groupsToDisassociate
) => {
try {
await OrganizationsAPI.update(organization.id, values);
await this.submitInstanceGroups(groupsToAssociate, groupsToDisassociate);
this.handleSuccess();
} catch (err) {
this.setState({ error: err });
}
}
handleCancel() {
const {
organization: { id },
history,
} = this.props;
history.push(`/organizations/${id}/details`);
}
handleSuccess() {
const {
organization: { id },
history,
} = this.props;
history.push(`/organizations/${id}/details`);
}
async submitInstanceGroups(groupsToAssociate, groupsToDisassociate) {
const { organization } = this.props;
try {
await Promise.all(
groupsToAssociate.map(id =>
OrganizationsAPI.associateInstanceGroup(organization.id, id)
@ -62,14 +30,15 @@ class OrganizationEdit extends Component {
OrganizationsAPI.disassociateInstanceGroup(organization.id, id)
)
);
} catch (err) {
this.setState({ error: err });
}
history.push(detailsUrl);
} catch (error) {
setFormError(error);
}
};
render() {
const { organization } = this.props;
const { error } = this.state;
const handleCancel = () => {
history.push(detailsUrl);
};
return (
<CardBody>
@ -77,16 +46,15 @@ class OrganizationEdit extends Component {
{({ me }) => (
<OrganizationForm
organization={organization}
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
handleSubmit={handleSubmit}
handleCancel={handleCancel}
me={me || {}}
/>
)}
</Config>
{error ? <div>error</div> : null}
{formError ? <div>error</div> : null}
</CardBody>
);
}
}
OrganizationEdit.propTypes = {
@ -98,4 +66,4 @@ OrganizationEdit.contextTypes = {
};
export { OrganizationEdit as _OrganizationEdit };
export default withRouter(OrganizationEdit);
export default OrganizationEdit;

View File

@ -1,5 +1,5 @@
import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import { useLocation, useRouteMatch } from 'react-router-dom';
import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { Card, PageSection } from '@patternfly/react-core';
@ -22,90 +22,26 @@ const QS_CONFIG = getQSConfig('organization', {
order_by: 'name',
});
class OrganizationsList extends Component {
constructor(props) {
super(props);
function OrganizationsList({ i18n }) {
const location = useLocation();
const match = useRouteMatch();
const [contentError, setContentError] = useState(null);
const [deletionError, setDeletionError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(true);
const [itemCount, setItemCount] = useState(0);
const [organizations, setOrganizations] = useState([]);
const [orgActions, setOrgActions] = useState(null);
const [selected, setSelected] = useState([]);
this.state = {
hasContentLoading: true,
contentError: null,
deletionError: null,
organizations: [],
selected: [],
itemCount: 0,
actions: null,
};
const addUrl = `${match.url}/add`;
const canAdd = orgActions && orgActions.POST;
const isAllSelected =
selected.length === organizations.length && selected.length > 0;
this.handleSelectAll = this.handleSelectAll.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleOrgDelete = this.handleOrgDelete.bind(this);
this.handleDeleteErrorClose = this.handleDeleteErrorClose.bind(this);
this.loadOrganizations = this.loadOrganizations.bind(this);
}
componentDidMount() {
this.loadOrganizations();
}
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.loadOrganizations();
}
}
handleSelectAll(isSelected) {
const { organizations } = this.state;
const selected = isSelected ? [...organizations] : [];
this.setState({ selected });
}
handleSelect(row) {
const { selected } = this.state;
if (selected.some(s => s.id === row.id)) {
this.setState({ selected: selected.filter(s => s.id !== row.id) });
} else {
this.setState({ selected: selected.concat(row) });
}
}
handleDeleteErrorClose() {
this.setState({ deletionError: null });
}
async handleOrgDelete() {
const { selected } = this.state;
this.setState({ hasContentLoading: true });
try {
await Promise.all(selected.map(org => OrganizationsAPI.destroy(org.id)));
} catch (err) {
this.setState({ deletionError: err });
} finally {
await this.loadOrganizations();
}
}
async loadOrganizations() {
const { location } = this.props;
const { actions: cachedActions } = this.state;
const params = parseQueryString(QS_CONFIG, location.search);
let optionsPromise;
if (cachedActions) {
optionsPromise = Promise.resolve({ data: { actions: cachedActions } });
} else {
optionsPromise = OrganizationsAPI.readOptions();
}
const promises = Promise.all([
OrganizationsAPI.read(params),
optionsPromise,
]);
this.setState({ contentError: null, hasContentLoading: true });
const loadOrganizations = async ({ search }) => {
const params = parseQueryString(QS_CONFIG, search);
setContentError(null);
setHasContentLoading(true);
try {
const [
{
@ -114,39 +50,65 @@ class OrganizationsList extends Component {
{
data: { actions },
},
] = await promises;
this.setState({
actions,
itemCount: count,
organizations: results,
selected: [],
});
} catch (err) {
this.setState({ contentError: err });
] = await Promise.all([
OrganizationsAPI.read(params),
loadOrganizationActions(),
]);
setItemCount(count);
setOrganizations(results);
setOrgActions(actions);
setSelected([]);
} catch (error) {
setContentError(error);
} finally {
this.setState({ hasContentLoading: false });
setHasContentLoading(false);
}
};
const loadOrganizationActions = () => {
if (orgActions) {
return Promise.resolve({ data: { actions: orgActions } });
}
return OrganizationsAPI.readOptions();
};
render() {
const {
actions,
itemCount,
contentError,
hasContentLoading,
deletionError,
selected,
organizations,
} = this.state;
const { match, i18n } = this.props;
const handleOrgDelete = async () => {
setHasContentLoading(true);
try {
await Promise.all(selected.map(({ id }) => OrganizationsAPI.destroy(id)));
} catch (error) {
setDeletionError(error);
} finally {
await loadOrganizations(location);
}
};
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected =
selected.length === organizations.length && selected.length > 0;
const handleSelectAll = isSelected => {
if (isSelected) {
setSelected(organizations);
} else {
setSelected([]);
}
};
const handleSelect = row => {
if (selected.some(s => s.id === row.id)) {
setSelected(selected.filter(s => s.id !== row.id));
} else {
setSelected(selected.concat(row));
}
};
const handleDeleteErrorClose = () => {
setDeletionError(null);
};
useEffect(() => {
loadOrganizations(location);
}, [location]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Fragment>
<>
<PageSection>
<Card>
<PaginatedDataList
@ -181,17 +143,17 @@ class OrganizationsList extends Component {
{...props}
showSelectAll
isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll}
onSelectAll={handleSelectAll}
qsConfig={QS_CONFIG}
additionalControls={[
<ToolbarDeleteButton
key="delete"
onDelete={this.handleOrgDelete}
onDelete={handleOrgDelete}
itemsToDelete={selected}
pluralizedItemName="Organizations"
/>,
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
<ToolbarAddButton key="add" linkTo={addUrl} />
) : null,
]}
/>
@ -202,13 +164,11 @@ class OrganizationsList extends Component {
organization={o}
detailUrl={`${match.url}/${o.id}`}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => this.handleSelect(o)}
onSelect={() => handleSelect(o)}
/>
)}
emptyStateControls={
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
) : null
canAdd ? <ToolbarAddButton key="add" linkTo={addUrl} /> : null
}
/>
</Card>
@ -217,15 +177,14 @@ class OrganizationsList extends Component {
isOpen={deletionError}
variant="danger"
title={i18n._(t`Error!`)}
onClose={this.handleDeleteErrorClose}
onClose={handleDeleteErrorClose}
>
{i18n._(t`Failed to delete one or more organizations.`)}
<ErrorDetail error={deletionError} />
</AlertModal>
</Fragment>
</>
);
}
}
export { OrganizationsList as _OrganizationsList };
export default withI18n()(withRouter(OrganizationsList));
export default withI18n()(OrganizationsList);

View File

@ -1,12 +1,14 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { OrganizationsAPI } from '@api';
import { mountWithContexts, waitForElement } from '@testUtils/enzymeHelpers';
import OrganizationsList, { _OrganizationsList } from './OrganizationList';
import OrganizationsList from './OrganizationList';
jest.mock('@api');
const mockAPIOrgsList = {
const mockOrganizations = {
data: {
count: 3,
results: [
@ -61,17 +63,9 @@ const mockAPIOrgsList = {
describe('<OrganizationsList />', () => {
let wrapper;
beforeEach(() => {
OrganizationsAPI.read = () =>
Promise.resolve({
data: {
count: 0,
results: [],
},
});
OrganizationsAPI.readOptions = () =>
Promise.resolve({
OrganizationsAPI.read.mockResolvedValue(mockOrganizations);
OrganizationsAPI.readOptions.mockResolvedValue({
data: {
actions: {
GET: {},
@ -80,78 +74,154 @@ describe('<OrganizationsList />', () => {
},
});
});
afterEach(() => {
jest.clearAllMocks();
});
test('initially renders succesfully', () => {
test('Initially renders succesfully', async () => {
await act(async () => {
mountWithContexts(<OrganizationsList />);
});
test('Puts 1 selected Org in state when handleSelect is called.', () => {
wrapper = mountWithContexts(<OrganizationsList />).find(
'OrganizationsList'
);
wrapper.setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
});
test('Items are rendered after loading', async () => {
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
expect(wrapper.find('OrganizationListItem').length).toBe(3);
});
test('Item appears selected after selecting it', async () => {
const itemCheckboxInput = 'input#select-organization-1';
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
await act(async () => {
wrapper
.find(itemCheckboxInput)
.closest('DataListCheck')
.props()
.onChange();
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find(itemCheckboxInput).props().checked === true
);
});
test('All items appear selected after select-all and unselected after unselect-all', async () => {
const itemCheckboxInputs = [
'input#select-organization-1',
'input#select-organization-2',
'input#select-organization-3',
];
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
// Check for initially unselected items
await waitForElement(
wrapper,
'input#select-all',
el => el.props().checked === false
);
itemCheckboxInputs.forEach(inputSelector => {
const checkboxInput = wrapper
.find('OrganizationsList')
.find(inputSelector);
expect(checkboxInput.props().checked === false);
});
// Check select-all behavior
await act(async () => {
wrapper
.find('Checkbox#select-all')
.props()
.onChange(true);
});
await waitForElement(
wrapper,
'input#select-all',
el => el.props().checked === true
);
itemCheckboxInputs.forEach(inputSelector => {
const checkboxInput = wrapper
.find('OrganizationsList')
.find(inputSelector);
expect(checkboxInput.props().checked === true);
});
// Check unselect-all behavior
await act(async () => {
wrapper
.find('Checkbox#select-all')
.props()
.onChange(false);
});
await waitForElement(
wrapper,
'input#select-all',
el => el.props().checked === false
);
itemCheckboxInputs.forEach(inputSelector => {
const checkboxInput = wrapper
.find('OrganizationsList')
.find(inputSelector);
expect(checkboxInput.props().checked === false);
});
});
test('Expected api calls are made for multi-delete', async () => {
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
expect(OrganizationsAPI.read).toHaveBeenCalledTimes(1);
await act(async () => {
wrapper
.find('Checkbox#select-all')
.props()
.onChange(true);
});
await waitForElement(
wrapper,
'input#select-all',
el => el.props().checked === true
);
await act(async () => {
wrapper.find('button[aria-label="Delete"]').simulate('click');
wrapper.update();
expect(wrapper.state('selected').length).toBe(0);
wrapper.instance().handleSelect(mockAPIOrgsList.data.results.slice(0, 1));
expect(wrapper.state('selected').length).toBe(1);
});
test('Puts all Orgs in state when handleSelectAll is called.', () => {
wrapper = mountWithContexts(<OrganizationsList />);
const list = wrapper.find('OrganizationsList');
list.setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
});
expect(list.state('selected').length).toBe(0);
list.instance().handleSelectAll(true);
wrapper.update();
expect(list.state('selected').length).toEqual(
list.state('organizations').length
const deleteButton = global.document.querySelector(
'body div[role="dialog"] button[aria-label="confirm delete"]'
);
expect(deleteButton).not.toEqual(null);
await act(async () => {
deleteButton.click();
});
expect(OrganizationsAPI.destroy).toHaveBeenCalledTimes(3);
expect(OrganizationsAPI.read).toHaveBeenCalledTimes(2);
});
test('api is called to delete Orgs for each org in selected.', () => {
wrapper = mountWithContexts(<OrganizationsList />);
const component = wrapper.find('OrganizationsList');
wrapper.find('OrganizationsList').setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
isModalOpen: mockAPIOrgsList.isModalOpen,
selected: mockAPIOrgsList.data.results,
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
expect(OrganizationsAPI.destroy).toHaveBeenCalledTimes(
component.state('selected').length
);
});
test('call loadOrganizations after org(s) have been deleted', () => {
const fetchOrgs = jest.spyOn(
_OrganizationsList.prototype,
'loadOrganizations'
);
const event = { preventDefault: () => {} };
wrapper = mountWithContexts(<OrganizationsList />);
wrapper.find('OrganizationsList').setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPIOrgsList.data.results.slice(0, 1),
});
const component = wrapper.find('OrganizationsList');
component.instance().handleOrgDelete(event);
expect(fetchOrgs).toBeCalled();
});
test('error is shown when org not successfully deleted from api', async done => {
test('Error dialog shown for failed deletion', async () => {
const itemCheckboxInput = 'input#select-organization-1';
OrganizationsAPI.destroy.mockRejectedValue(
new Error({
response: {
@ -163,60 +233,72 @@ describe('<OrganizationsList />', () => {
},
})
);
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
wrapper.find('OrganizationsList').setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPIOrgsList.data.results.slice(0, 1),
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
await act(async () => {
wrapper
.find(itemCheckboxInput)
.closest('DataListCheck')
.props()
.onChange();
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find(itemCheckboxInput).props().checked === true
);
await act(async () => {
wrapper.find('button[aria-label="Delete"]').simulate('click');
wrapper.update();
});
const deleteButton = global.document.querySelector(
'body div[role="dialog"] button[aria-label="confirm delete"]'
);
expect(deleteButton).not.toEqual(null);
await act(async () => {
deleteButton.click();
});
await waitForElement(
wrapper,
'Modal',
el => el.props().isOpen === true && el.props().title === 'Error!'
);
done();
});
test('Add button shown for users without ability to POST', async done => {
test('Add button shown for users with ability to POST', async () => {
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.state('hasContentLoading') === true
);
await waitForElement(
wrapper,
'OrganizationsList',
el => el.state('hasContentLoading') === false
el => el.find('ContentLoading').length === 0
);
expect(wrapper.find('ToolbarAddButton').length).toBe(1);
done();
});
test('Add button hidden for users without ability to POST', async done => {
OrganizationsAPI.readOptions = () =>
Promise.resolve({
test('Add button hidden for users without ability to POST', async () => {
OrganizationsAPI.readOptions.mockResolvedValue({
data: {
actions: {
GET: {},
},
},
});
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.state('hasContentLoading') === true
);
await waitForElement(
wrapper,
'OrganizationsList',
el => el.state('hasContentLoading') === false
el => el.find('ContentLoading').length === 0
);
expect(wrapper.find('ToolbarAddButton').length).toBe(0);
done();
});
});

View File

@ -40,16 +40,13 @@ const ListGroup = styled.span`
}
`;
class OrganizationListItem extends React.Component {
static propTypes = {
organization: Organization.isRequired,
detailUrl: string.isRequired,
isSelected: bool.isRequired,
onSelect: func.isRequired,
};
render() {
const { organization, isSelected, onSelect, detailUrl, i18n } = this.props;
function OrganizationListItem({
organization,
isSelected,
onSelect,
detailUrl,
i18n,
}) {
const labelId = `check-action-${organization.id}`;
return (
<DataListItem key={organization.id} aria-labelledby={labelId}>
@ -86,10 +83,7 @@ class OrganizationListItem extends React.Component {
</DataListCell>,
<ActionButtonCell lastcolumn="true" key="action">
{organization.summary_fields.user_capabilities.edit && (
<Tooltip
content={i18n._(t`Edit Organization`)}
position="top"
>
<Tooltip content={i18n._(t`Edit Organization`)} position="top">
<ListActionButton
variant="plain"
component={Link}
@ -105,6 +99,13 @@ class OrganizationListItem extends React.Component {
</DataListItemRow>
</DataListItem>
);
}
}
OrganizationListItem.propTypes = {
organization: Organization.isRequired,
detailUrl: string.isRequired,
isSelected: bool.isRequired,
onSelect: func.isRequired,
};
export default withI18n()(OrganizationListItem);

View File

@ -1,6 +1,6 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { useLocation } from 'react-router-dom';
import { OrganizationsAPI } from '@api';
import PaginatedDataList from '@components/PaginatedDataList';
@ -12,53 +12,32 @@ const QS_CONFIG = getQSConfig('team', {
order_by: 'name',
});
class OrganizationTeams extends React.Component {
constructor(props) {
super(props);
function OrganizationTeams({ id }) {
const location = useLocation();
const [contentError, setContentError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(false);
const [itemCount, setItemCount] = useState(0);
const [teams, setTeams] = useState([]);
this.loadOrganizationTeamsList = this.loadOrganizationTeamsList.bind(this);
this.state = {
contentError: null,
hasContentLoading: true,
itemCount: 0,
teams: [],
};
}
componentDidMount() {
this.loadOrganizationTeamsList();
}
componentDidUpdate(prevProps) {
const { location } = this.props;
if (location !== prevProps.location) {
this.loadOrganizationTeamsList();
}
}
async loadOrganizationTeamsList() {
const { id, location } = this.props;
useEffect(() => {
(async () => {
const params = parseQueryString(QS_CONFIG, location.search);
this.setState({ hasContentLoading: true, contentError: null });
setContentError(null);
setHasContentLoading(true);
try {
const {
data: { count = 0, results = [] },
} = await OrganizationsAPI.readTeams(id, params);
this.setState({
itemCount: count,
teams: results,
});
} catch (err) {
this.setState({ contentError: err });
setItemCount(count);
setTeams(results);
} catch (error) {
setContentError(error);
} finally {
this.setState({ hasContentLoading: false });
}
setHasContentLoading(false);
}
})();
}, [id, location]);
render() {
const { contentError, hasContentLoading, teams, itemCount } = this.state;
return (
<PaginatedDataList
contentError={contentError}
@ -69,7 +48,6 @@ class OrganizationTeams extends React.Component {
qsConfig={QS_CONFIG}
/>
);
}
}
OrganizationTeams.propTypes = {
@ -77,4 +55,4 @@ OrganizationTeams.propTypes = {
};
export { OrganizationTeams as _OrganizationTeams };
export default withRouter(OrganizationTeams);
export default OrganizationTeams;

View File

@ -1,5 +1,5 @@
import React from 'react';
import { shallow } from 'enzyme';
import { act } from 'react-dom/test-utils';
import { OrganizationsAPI } from '@api';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
@ -31,8 +31,9 @@ describe('<OrganizationTeams />', () => {
jest.clearAllMocks();
});
test('renders succesfully', () => {
shallow(
test('renders succesfully', async () => {
await act(async () => {
mountWithContexts(
<OrganizationTeams
id={1}
searchString=""
@ -40,11 +41,14 @@ describe('<OrganizationTeams />', () => {
/>
);
});
});
test('should load teams on mount', () => {
test('should load teams on mount', async () => {
await act(async () => {
mountWithContexts(<OrganizationTeams id={1} searchString="" />).find(
'OrganizationTeams'
);
});
expect(OrganizationsAPI.readTeams).toHaveBeenCalledWith(1, {
page: 1,
page_size: 5,
@ -53,10 +57,10 @@ describe('<OrganizationTeams />', () => {
});
test('should pass fetched teams to PaginatedDatalist', async () => {
const wrapper = mountWithContexts(
<OrganizationTeams id={1} searchString="" />
);
let wrapper;
await act(async () => {
wrapper = mountWithContexts(<OrganizationTeams id={1} searchString="" />);
});
await sleep(0);
wrapper.update();

View File

@ -1,11 +1,14 @@
import React from 'react';
import { act } from 'react-dom/test-utils';
import { mountWithContexts } from '@testUtils/enzymeHelpers';
import Organizations from './Organizations';
jest.mock('@api');
describe('<Organizations />', () => {
test('initially renders succesfully', () => {
test('initially renders succesfully', async () => {
await act(async () => {
mountWithContexts(
<Organizations
match={{ path: '/organizations', url: '/organizations' }}
@ -13,4 +16,5 @@ describe('<Organizations />', () => {
/>
);
});
});
});