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,117 +16,92 @@ const CardBody = styled(PFCardBody)`
padding-top: 20px;
`;
class OrganizationDetail extends Component {
constructor(props) {
super(props);
function OrganizationDetail({ i18n, organization }) {
const {
params: { id },
} = useRouteMatch();
const {
name,
description,
custom_virtualenv,
max_hosts,
created,
modified,
summary_fields,
} = organization;
const [contentError, setContentError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(true);
const [instanceGroups, setInstanceGroups] = useState([]);
this.state = {
contentError: null,
hasContentLoading: true,
instanceGroups: [],
};
this.loadInstanceGroups = this.loadInstanceGroups.bind(this);
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 />;
}
componentDidMount() {
this.loadInstanceGroups();
if (contentError) {
return <ContentError error={contentError} />;
}
async loadInstanceGroups() {
const {
match: {
params: { id },
},
} = this.props;
this.setState({ hasContentLoading: true });
try {
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,
max_hosts,
created,
modified,
summary_fields,
},
match,
i18n,
} = this.props;
if (hasContentLoading) {
return <ContentLoading />;
}
if (contentError) {
return <ContentError error={contentError} />;
}
return (
<CardBody>
<DetailList>
return (
<CardBody>
<DetailList>
<Detail
label={i18n._(t`Name`)}
value={name}
dataCy="organization-detail-name"
/>
<Detail label={i18n._(t`Description`)} value={description} />
<Detail label={i18n._(t`Max Hosts`)} value={`${max_hosts}`} />
<Detail
label={i18n._(t`Ansible Environment`)}
value={custom_virtualenv}
/>
<Detail label={i18n._(t`Created`)} value={formatDateString(created)} />
<Detail
label={i18n._(t`Last Modified`)}
value={formatDateString(modified)}
/>
{instanceGroups && instanceGroups.length > 0 && (
<Detail
label={i18n._(t`Name`)}
value={name}
dataCy="organization-detail-name"
fullWidth
label={i18n._(t`Instance Groups`)}
value={
<ChipGroup numChips={5}>
{instanceGroups.map(ig => (
<Chip key={ig.id} isReadOnly>
{ig.name}
</Chip>
))}
</ChipGroup>
}
/>
<Detail label={i18n._(t`Description`)} value={description} />
<Detail label={i18n._(t`Max Hosts`)} value={`${max_hosts}`} />
<Detail
label={i18n._(t`Ansible Environment`)}
value={custom_virtualenv}
/>
<Detail
label={i18n._(t`Created`)}
value={formatDateString(created)}
/>
<Detail
label={i18n._(t`Last Modified`)}
value={formatDateString(modified)}
/>
{instanceGroups && instanceGroups.length > 0 && (
<Detail
fullWidth
label={i18n._(t`Instance Groups`)}
value={
<ChipGroup numChips={5}>
{instanceGroups.map(ig => (
<Chip key={ig.id} isReadOnly>
{ig.name}
</Chip>
))}
</ChipGroup>
}
/>
)}
</DetailList>
{summary_fields.user_capabilities.edit && (
<div css="margin-top: 10px; text-align: right;">
<Button
component={Link}
to={`/organizations/${match.params.id}/edit`}
>
{i18n._(t`Edit`)}
</Button>
</div>
)}
</CardBody>
);
}
</DetailList>
{summary_fields.user_capabilities.edit && (
<div css="margin-top: 10px; text-align: right;">
<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', () => {
mountWithContexts(<OrganizationDetail organization={mockOrganization} />);
test('initially renders succesfully', async () => {
await act(async () => {
mountWithContexts(<OrganizationDetail organization={mockOrganization} />);
});
});
test('should request instance groups from api', () => {
mountWithContexts(<OrganizationDetail organization={mockOrganization} />);
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(
<OrganizationDetail organization={mockOrganization} />
);
const component = await waitForElement(wrapper, 'OrganizationDetail');
expect(component.state().instanceGroups).toEqual(
mockInstanceGroups.data.results
);
done();
test('should render the expected instance group', async () => {
let component;
await act(async () => {
component = mountWithContexts(
<OrganizationDetail organization={mockOrganization} />
);
});
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(
<OrganizationDetail organization={mockOrganization} />
);
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(
<OrganizationDetail organization={mockOrganization} />
);
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(
<OrganizationDetail organization={readOnlyOrg} />
);
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,31 +30,31 @@ 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>
<Config>
{({ me }) => (
<OrganizationForm
organization={organization}
handleSubmit={this.handleSubmit}
handleCancel={this.handleCancel}
me={me || {}}
/>
)}
</Config>
{error ? <div>error</div> : null}
</CardBody>
);
}
return (
<CardBody>
<Config>
{({ me }) => (
<OrganizationForm
organization={organization}
handleSubmit={handleSubmit}
handleCancel={handleCancel}
me={me || {}}
/>
)}
</Config>
{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,118 +50,141 @@ 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);
}
}
};
render() {
const {
actions,
itemCount,
contentError,
hasContentLoading,
deletionError,
selected,
organizations,
} = this.state;
const { match, i18n } = this.props;
const loadOrganizationActions = () => {
if (orgActions) {
return Promise.resolve({ data: { actions: orgActions } });
}
return OrganizationsAPI.readOptions();
};
const canAdd =
actions && Object.prototype.hasOwnProperty.call(actions, 'POST');
const isAllSelected =
selected.length === organizations.length && selected.length > 0;
const handleOrgDelete = async () => {
setHasContentLoading(true);
try {
await Promise.all(selected.map(({ id }) => OrganizationsAPI.destroy(id)));
} catch (error) {
setDeletionError(error);
} finally {
await loadOrganizations(location);
}
};
return (
<Fragment>
<PageSection>
<Card>
<PaginatedDataList
contentError={contentError}
hasContentLoading={hasContentLoading}
items={organizations}
itemCount={itemCount}
pluralizedItemName="Organizations"
qsConfig={QS_CONFIG}
toolbarColumns={[
{
name: i18n._(t`Name`),
key: 'name',
isSortable: true,
isSearchable: true,
},
{
name: i18n._(t`Modified`),
key: 'modified',
isSortable: true,
isNumeric: true,
},
{
name: i18n._(t`Created`),
key: 'created',
isSortable: true,
isNumeric: true,
},
]}
renderToolbar={props => (
<DataListToolbar
{...props}
showSelectAll
isAllSelected={isAllSelected}
onSelectAll={this.handleSelectAll}
qsConfig={QS_CONFIG}
additionalControls={[
<ToolbarDeleteButton
key="delete"
onDelete={this.handleOrgDelete}
itemsToDelete={selected}
pluralizedItemName="Organizations"
/>,
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
) : null,
]}
/>
)}
renderItem={o => (
<OrganizationListItem
key={o.id}
organization={o}
detailUrl={`${match.url}/${o.id}`}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => this.handleSelect(o)}
/>
)}
emptyStateControls={
canAdd ? (
<ToolbarAddButton key="add" linkTo={`${match.url}/add`} />
) : null
}
/>
</Card>
</PageSection>
<AlertModal
isOpen={deletionError}
variant="danger"
title={i18n._(t`Error!`)}
onClose={this.handleDeleteErrorClose}
>
{i18n._(t`Failed to delete one or more organizations.`)}
<ErrorDetail error={deletionError} />
</AlertModal>
</Fragment>
);
}
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 (
<>
<PageSection>
<Card>
<PaginatedDataList
contentError={contentError}
hasContentLoading={hasContentLoading}
items={organizations}
itemCount={itemCount}
pluralizedItemName="Organizations"
qsConfig={QS_CONFIG}
toolbarColumns={[
{
name: i18n._(t`Name`),
key: 'name',
isSortable: true,
isSearchable: true,
},
{
name: i18n._(t`Modified`),
key: 'modified',
isSortable: true,
isNumeric: true,
},
{
name: i18n._(t`Created`),
key: 'created',
isSortable: true,
isNumeric: true,
},
]}
renderToolbar={props => (
<DataListToolbar
{...props}
showSelectAll
isAllSelected={isAllSelected}
onSelectAll={handleSelectAll}
qsConfig={QS_CONFIG}
additionalControls={[
<ToolbarDeleteButton
key="delete"
onDelete={handleOrgDelete}
itemsToDelete={selected}
pluralizedItemName="Organizations"
/>,
canAdd ? (
<ToolbarAddButton key="add" linkTo={addUrl} />
) : null,
]}
/>
)}
renderItem={o => (
<OrganizationListItem
key={o.id}
organization={o}
detailUrl={`${match.url}/${o.id}`}
isSelected={selected.some(row => row.id === o.id)}
onSelect={() => handleSelect(o)}
/>
)}
emptyStateControls={
canAdd ? <ToolbarAddButton key="add" linkTo={addUrl} /> : null
}
/>
</Card>
</PageSection>
<AlertModal
isOpen={deletionError}
variant="danger"
title={i18n._(t`Error!`)}
onClose={handleDeleteErrorClose}
>
{i18n._(t`Failed to delete one or more organizations.`)}
<ErrorDetail error={deletionError} />
</AlertModal>
</>
);
}
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,97 +63,165 @@ const mockAPIOrgsList = {
describe('<OrganizationsList />', () => {
let wrapper;
beforeEach(() => {
OrganizationsAPI.read = () =>
Promise.resolve({
data: {
count: 0,
results: [],
OrganizationsAPI.read.mockResolvedValue(mockOrganizations);
OrganizationsAPI.readOptions.mockResolvedValue({
data: {
actions: {
GET: {},
POST: {},
},
});
OrganizationsAPI.readOptions = () =>
Promise.resolve({
data: {
actions: {
GET: {},
POST: {},
},
},
});
},
});
});
afterEach(() => {
jest.clearAllMocks();
});
test('initially renders succesfully', () => {
mountWithContexts(<OrganizationsList />);
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'
test('Items are rendered after loading', async () => {
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
await waitForElement(
wrapper,
'OrganizationsList',
el => el.find('ContentLoading').length === 0
);
wrapper.setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
});
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);
expect(wrapper.find('OrganizationListItem').length).toBe(3);
});
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,
test('Item appears selected after selecting it', async () => {
const itemCheckboxInput = 'input#select-organization-1';
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
expect(list.state('selected').length).toBe(0);
list.instance().handleSelectAll(true);
wrapper.update();
expect(list.state('selected').length).toEqual(
list.state('organizations').length
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('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,
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 />);
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
expect(OrganizationsAPI.destroy).toHaveBeenCalledTimes(
component.state('selected').length
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('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),
test('Expected api calls are made for multi-delete', async () => {
await act(async () => {
wrapper = mountWithContexts(<OrganizationsList />);
});
const component = wrapper.find('OrganizationsList');
component.instance().handleOrgDelete(event);
expect(fetchOrgs).toBeCalled();
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();
});
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('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 />', () => {
},
})
);
wrapper = mountWithContexts(<OrganizationsList />);
wrapper.find('OrganizationsList').setState({
organizations: mockAPIOrgsList.data.results,
itemCount: 3,
isInitialized: true,
selected: mockAPIOrgsList.data.results.slice(0, 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
);
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();
});
wrapper.find('ToolbarDeleteButton').prop('onDelete')();
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 => {
wrapper = mountWithContexts(<OrganizationsList />);
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({
data: {
actions: {
GET: {},
},
test('Add button hidden for users without ability to POST', async () => {
OrganizationsAPI.readOptions.mockResolvedValue({
data: {
actions: {
GET: {},
},
});
wrapper = mountWithContexts(<OrganizationsList />);
},
});
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,71 +40,72 @@ 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;
const labelId = `check-action-${organization.id}`;
return (
<DataListItem key={organization.id} aria-labelledby={labelId}>
<DataListItemRow>
<DataListCheck
id={`select-organization-${organization.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={labelId}
/>
<DataListItemCells
dataListCells={[
<DataListCell key="divider">
<VerticalSeparator />
<span id={labelId}>
<Link to={`${detailUrl}`}>
<b>{organization.name}</b>
</Link>
</span>
</DataListCell>,
<DataListCell key="related-field-counts">
<ListGroup>
{i18n._(t`Members`)}
<Badge isRead>
{organization.summary_fields.related_field_counts.users}
</Badge>
</ListGroup>
<ListGroup>
{i18n._(t`Teams`)}
<Badge isRead>
{organization.summary_fields.related_field_counts.teams}
</Badge>
</ListGroup>
</DataListCell>,
<ActionButtonCell lastcolumn="true" key="action">
{organization.summary_fields.user_capabilities.edit && (
<Tooltip
content={i18n._(t`Edit Organization`)}
position="top"
function OrganizationListItem({
organization,
isSelected,
onSelect,
detailUrl,
i18n,
}) {
const labelId = `check-action-${organization.id}`;
return (
<DataListItem key={organization.id} aria-labelledby={labelId}>
<DataListItemRow>
<DataListCheck
id={`select-organization-${organization.id}`}
checked={isSelected}
onChange={onSelect}
aria-labelledby={labelId}
/>
<DataListItemCells
dataListCells={[
<DataListCell key="divider">
<VerticalSeparator />
<span id={labelId}>
<Link to={`${detailUrl}`}>
<b>{organization.name}</b>
</Link>
</span>
</DataListCell>,
<DataListCell key="related-field-counts">
<ListGroup>
{i18n._(t`Members`)}
<Badge isRead>
{organization.summary_fields.related_field_counts.users}
</Badge>
</ListGroup>
<ListGroup>
{i18n._(t`Teams`)}
<Badge isRead>
{organization.summary_fields.related_field_counts.teams}
</Badge>
</ListGroup>
</DataListCell>,
<ActionButtonCell lastcolumn="true" key="action">
{organization.summary_fields.user_capabilities.edit && (
<Tooltip content={i18n._(t`Edit Organization`)} position="top">
<ListActionButton
variant="plain"
component={Link}
to={`/organizations/${organization.id}/edit`}
>
<ListActionButton
variant="plain"
component={Link}
to={`/organizations/${organization.id}/edit`}
>
<PencilAltIcon />
</ListActionButton>
</Tooltip>
)}
</ActionButtonCell>,
]}
/>
</DataListItemRow>
</DataListItem>
);
}
<PencilAltIcon />
</ListActionButton>
</Tooltip>
)}
</ActionButtonCell>,
]}
/>
</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,64 +12,42 @@ 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);
useEffect(() => {
(async () => {
const params = parseQueryString(QS_CONFIG, location.search);
setContentError(null);
setHasContentLoading(true);
try {
const {
data: { count = 0, results = [] },
} = await OrganizationsAPI.readTeams(id, params);
setItemCount(count);
setTeams(results);
} catch (error) {
setContentError(error);
} finally {
setHasContentLoading(false);
}
})();
}, [id, location]);
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;
const params = parseQueryString(QS_CONFIG, location.search);
this.setState({ hasContentLoading: true, contentError: null });
try {
const {
data: { count = 0, results = [] },
} = await OrganizationsAPI.readTeams(id, params);
this.setState({
itemCount: count,
teams: results,
});
} catch (err) {
this.setState({ contentError: err });
} finally {
this.setState({ hasContentLoading: false });
}
}
render() {
const { contentError, hasContentLoading, teams, itemCount } = this.state;
return (
<PaginatedDataList
contentError={contentError}
hasContentLoading={hasContentLoading}
items={teams}
itemCount={itemCount}
pluralizedItemName="Teams"
qsConfig={QS_CONFIG}
/>
);
}
return (
<PaginatedDataList
contentError={contentError}
hasContentLoading={hasContentLoading}
items={teams}
itemCount={itemCount}
pluralizedItemName="Teams"
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,20 +31,24 @@ describe('<OrganizationTeams />', () => {
jest.clearAllMocks();
});
test('renders succesfully', () => {
shallow(
<OrganizationTeams
id={1}
searchString=""
location={{ search: '', pathname: '/organizations/1/teams' }}
/>
);
test('renders succesfully', async () => {
await act(async () => {
mountWithContexts(
<OrganizationTeams
id={1}
searchString=""
location={{ search: '', pathname: '/organizations/1/teams' }}
/>
);
});
});
test('should load teams on mount', () => {
mountWithContexts(<OrganizationTeams id={1} searchString="" />).find(
'OrganizationTeams'
);
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,16 +1,20 @@
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', () => {
mountWithContexts(
<Organizations
match={{ path: '/organizations', url: '/organizations' }}
location={{ search: '', pathname: '/organizations' }}
/>
);
test('initially renders succesfully', async () => {
await act(async () => {
mountWithContexts(
<Organizations
match={{ path: '/organizations', url: '/organizations' }}
location={{ search: '', pathname: '/organizations' }}
/>
);
});
});
});