test: PropertiesModal (#13818)

* Tests for test-PropertiesModal

* finish fetchMock to solve conflicts

* clean fetchMock
This commit is contained in:
Bruno Motta
2021-04-05 15:24:10 -03:00
committed by GitHub
parent 203512e189
commit 592c566bb4
2 changed files with 279 additions and 2 deletions

View File

@@ -0,0 +1,277 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import { Slice } from 'src/types/Chart';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import PropertiesModal from '.';
const createProps = () => ({
slice: ({
cache_timeout: null,
changed_on: '2021-03-19T16:30:56.750230',
changed_on_humanized: '7 days ago',
datasource: 'FCC 2018 Survey',
description: null,
description_markeddown: '',
edit_url: '/chart/edit/318',
form_data: {
adhoc_filters: [],
all_columns_x: ['age'],
color_scheme: 'supersetColors',
datasource: '49__table',
granularity_sqla: 'time_start',
groupby: null,
label_colors: {},
link_length: '25',
queryFields: { groupby: 'groupby' },
row_limit: 10000,
slice_id: 318,
time_range: 'No filter',
time_range_endpoints: ['inclusive', 'exclusive'],
url_params: {},
viz_type: 'histogram',
x_axis_label: 'age',
y_axis_label: 'count',
},
modified: '<span class="no-wrap">7 days ago</span>',
owners: [
{
text: 'Superset Admin',
value: 1,
},
],
slice_id: 318,
slice_name: 'Age distribution of respondents',
slice_url: '/superset/explore/?form_data=%7B%22slice_id%22%3A%20318%7D',
} as unknown) as Slice,
show: true,
onHide: jest.fn(),
onSave: jest.fn(),
});
fetchMock.get('http://localhost/api/v1/chart/318', {
body: {
description_columns: {},
id: 318,
label_columns: {
cache_timeout: 'Cache Timeout',
'dashboards.dashboard_title': 'Dashboards Dashboard Title',
'dashboards.id': 'Dashboards Id',
description: 'Description',
'owners.first_name': 'Owners First Name',
'owners.id': 'Owners Id',
'owners.last_name': 'Owners Last Name',
'owners.username': 'Owners Username',
params: 'Params',
slice_name: 'Slice Name',
viz_type: 'Viz Type',
},
result: {
cache_timeout: null,
dashboards: [
{
dashboard_title: 'FCC New Coder Survey 2018',
id: 23,
},
],
description: null,
owners: [
{
first_name: 'Superset',
id: 1,
last_name: 'Admin',
username: 'admin',
},
],
params:
'{"adhoc_filters": [], "all_columns_x": ["age"], "color_scheme": "supersetColors", "datasource": "42__table", "granularity_sqla": "time_start", "groupby": null, "label_colors": {}, "link_length": "25", "queryFields": {"groupby": "groupby"}, "row_limit": 10000, "slice_id": 1380, "time_range": "No filter", "time_range_endpoints": ["inclusive", "exclusive"], "url_params": {}, "viz_type": "histogram", "x_axis_label": "age", "y_axis_label": "count"}',
slice_name: 'Age distribution of respondents',
viz_type: 'histogram',
},
show_columns: [
'cache_timeout',
'dashboards.dashboard_title',
'dashboards.id',
'description',
'owners.first_name',
'owners.id',
'owners.last_name',
'owners.username',
'params',
'slice_name',
'viz_type',
],
show_title: 'Show Slice',
},
});
fetchMock.get(
'http://localhost/api/v1/chart/related/owners?q=(filter:%27%27)',
{
body: {
count: 1,
result: [
{
text: 'Superset Admin',
value: 1,
},
],
},
sendAsJson: true,
},
);
fetchMock.put('http://localhost/api/v1/chart/318', {
body: {
id: 318,
result: {
cache_timeout: null,
description: null,
owners: [],
slice_name: 'Age distribution of respondents',
},
},
sendAsJson: true,
});
afterAll(() => {
fetchMock.resetBehavior();
});
test('Should render null when show:false', async () => {
const props = createProps();
props.show = false;
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(
screen.queryByRole('dialog', { name: 'Edit Chart Properties' }),
).not.toBeInTheDocument();
});
});
test('Should render when show:true', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(
screen.getByRole('dialog', { name: 'Edit Chart Properties' }),
).toBeVisible();
});
});
test('Should have modal header', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(screen.getByText('Edit Chart Properties')).toBeVisible();
expect(screen.getByText('×')).toBeVisible();
expect(screen.getByRole('button', { name: 'Close' })).toBeVisible();
});
});
test('"Close" button should call "onHide"', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(props.onHide).toBeCalledTimes(0);
});
userEvent.click(screen.getByRole('button', { name: 'Close' }));
await waitFor(() => {
expect(props.onHide).toBeCalledTimes(1);
expect(props.onSave).toBeCalledTimes(0);
});
});
test('Should render all elements inside modal', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(screen.getAllByRole('textbox')).toHaveLength(4);
expect(
screen.getByRole('heading', { name: 'Basic information' }),
).toBeVisible();
expect(screen.getByText('Name')).toBeVisible();
expect(screen.getByText('Description')).toBeVisible();
expect(
screen.getByRole('heading', { name: 'Configuration' }),
).toBeVisible();
expect(screen.getByText('Cache timeout')).toBeVisible();
expect(screen.getByRole('heading', { name: 'Access' })).toBeVisible();
expect(screen.getByText('Owners')).toBeVisible();
});
});
test('Should have modal footer', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(screen.getByText('Cancel')).toBeVisible();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeVisible();
expect(screen.getByText('Save')).toBeVisible();
expect(screen.getByRole('button', { name: 'Save' })).toBeVisible();
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
});
});
test('"Cancel" button should call "onHide"', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(props.onHide).toBeCalledTimes(0);
});
userEvent.click(screen.getByRole('button', { name: 'Cancel' }));
await waitFor(() => {
expect(props.onHide).toBeCalledTimes(1);
expect(props.onSave).toBeCalledTimes(0);
});
});
test('"Save" button should call only "onSave"', async () => {
const props = createProps();
render(<PropertiesModal {...props} />);
await waitFor(() => {
expect(props.onSave).toBeCalledTimes(0);
expect(props.onHide).toBeCalledTimes(0);
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled();
});
userEvent.click(screen.getByRole('button', { name: 'Save' }));
await waitFor(() => {
expect(props.onSave).toBeCalledTimes(1);
expect(props.onHide).toBeCalledTimes(1);
});
});

View File

@@ -0,0 +1,283 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useState, useEffect, useCallback } from 'react';
import {
Row,
Col,
FormControl,
FormGroup,
FormControlProps,
} from 'react-bootstrap';
import Modal from 'src/common/components/Modal';
import Button from 'src/components/Button';
import { OptionsType } from 'react-select/src/types';
import { AsyncSelect } from 'src/components/Select';
import rison from 'rison';
import { t, SupersetClient } from '@superset-ui/core';
import Chart, { Slice } from 'src/types/Chart';
import FormLabel from 'src/components/FormLabel';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
type PropertiesModalProps = {
slice: Slice;
show: boolean;
onHide: () => void;
onSave: (chart: Chart) => void;
};
type OwnerOption = {
label: string;
value: number;
};
export default function PropertiesModal({
slice,
onHide,
onSave,
show,
}: PropertiesModalProps) {
const [submitting, setSubmitting] = useState(false);
// values of form inputs
const [name, setName] = useState(slice.slice_name || '');
const [description, setDescription] = useState(slice.description || '');
const [cacheTimeout, setCacheTimeout] = useState(
slice.cache_timeout != null ? slice.cache_timeout : '',
);
const [owners, setOwners] = useState<OptionsType<OwnerOption> | null>(null);
function showError({ error, statusText, message }: any) {
let errorText = error || statusText || t('An error has occurred');
if (message === 'Forbidden') {
errorText = t('You do not have permission to edit this chart');
}
Modal.error({
title: 'Error',
content: errorText,
okButtonProps: { danger: true, className: 'btn-danger' },
});
}
const fetchChartData = useCallback(
async function fetchChartData() {
try {
const response = await SupersetClient.get({
endpoint: `/api/v1/chart/${slice.slice_id}`,
});
const chart = response.json.result;
setOwners(
chart.owners.map((owner: any) => ({
value: owner.id,
label: `${owner.first_name} ${owner.last_name}`,
})),
);
} catch (response) {
const clientError = await getClientErrorObject(response);
showError(clientError);
}
},
[slice.slice_id],
);
// get the owners of this slice
useEffect(() => {
fetchChartData();
}, [fetchChartData]);
// update name after it's changed in another modal
useEffect(() => {
setName(slice.slice_name || '');
}, [slice.slice_name]);
const loadOptions = (input = '') => {
const query = rison.encode({
filter: input,
});
return SupersetClient.get({
endpoint: `/api/v1/chart/related/owners?q=${query}`,
}).then(
response => {
const { result } = response.json;
return result.map((item: any) => ({
value: item.value,
label: item.text,
}));
},
badResponse => {
getClientErrorObject(badResponse).then(showError);
return [];
},
);
};
const onSubmit = async (event: React.FormEvent) => {
event.stopPropagation();
event.preventDefault();
setSubmitting(true);
const payload: { [key: string]: any } = {
slice_name: name || null,
description: description || null,
cache_timeout: cacheTimeout || null,
};
if (owners) {
payload.owners = owners.map(o => o.value);
}
try {
const res = await SupersetClient.put({
endpoint: `/api/v1/chart/${slice.slice_id}`,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
// update the redux state
const updatedChart = {
...res.json.result,
id: slice.slice_id,
};
onSave(updatedChart);
onHide();
} catch (res) {
const clientError = await getClientErrorObject(res);
showError(clientError);
}
setSubmitting(false);
};
return (
<Modal
show={show}
onHide={onHide}
title="Edit Chart Properties"
footer={
<>
<Button
data-test="properties-modal-cancel-button"
htmlType="button"
buttonSize="small"
onClick={onHide}
cta
>
{t('Cancel')}
</Button>
<Button
data-test="properties-modal-save-button"
htmlType="button"
buttonSize="small"
buttonStyle="primary"
// @ts-ignore
onClick={onSubmit}
disabled={!owners || submitting || !name}
cta
>
{t('Save')}
</Button>
</>
}
responsive
wrapProps={{ 'data-test': 'properties-edit-modal' }}
>
<form onSubmit={onSubmit}>
<Row>
<Col md={6}>
<h3>{t('Basic information')}</h3>
<FormGroup>
<FormLabel htmlFor="name" required>
{t('Name')}
</FormLabel>
<FormControl
name="name"
data-test="properties-modal-name-input"
type="text"
bsSize="sm"
value={name}
onChange={(
event: React.FormEvent<FormControl & FormControlProps>,
) => setName((event.currentTarget?.value as string) ?? '')}
/>
</FormGroup>
<FormGroup>
<FormLabel htmlFor="description">{t('Description')}</FormLabel>
<FormControl
name="description"
type="text"
componentClass="textarea"
bsSize="sm"
value={description}
onChange={(
event: React.FormEvent<FormControl & FormControlProps>,
) =>
setDescription((event.currentTarget?.value as string) ?? '')
}
style={{ maxWidth: '100%' }}
/>
<p className="help-block">
{t(
'The description can be displayed as widget headers in the dashboard view. Supports markdown.',
)}
</p>
</FormGroup>
</Col>
<Col md={6}>
<h3>{t('Configuration')}</h3>
<FormGroup>
<FormLabel htmlFor="cacheTimeout">{t('Cache timeout')}</FormLabel>
<FormControl
name="cacheTimeout"
type="text"
bsSize="sm"
value={cacheTimeout}
onChange={(
event: React.FormEvent<FormControl & FormControlProps>,
) => {
const targetValue =
(event.currentTarget?.value as string) ?? '';
setCacheTimeout(targetValue.replace(/[^0-9]/, ''));
}}
/>
<p className="help-block">
{t(
"Duration (in seconds) of the caching timeout for this chart. Note this defaults to the dataset's timeout if undefined.",
)}
</p>
</FormGroup>
<h3 style={{ marginTop: '1em' }}>{t('Access')}</h3>
<FormGroup>
<FormLabel htmlFor="owners">{t('Owners')}</FormLabel>
<AsyncSelect
isMulti
name="owners"
value={owners || []}
loadOptions={loadOptions}
defaultOptions // load options on render
cacheOptions
onChange={setOwners}
disabled={!owners}
filterOption={null} // options are filtered at the api
/>
<p className="help-block">
{t(
'A list of users who can alter the chart. Searchable by name or username.',
)}
</p>
</FormGroup>
</Col>
</Row>
</form>
</Modal>
);
}