test: DisplayQueryButton (#13750)

* Tests for DisplayQueryButton component

* add factories to props and fetch-mock

* Update superset-frontend/src/explore/components/DisplayQueryButton/DisplayQueryButton.test.tsx

Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com>

* Update superset-frontend/src/explore/components/DisplayQueryButton/DisplayQueryButton.test.tsx

Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com>

Co-authored-by: Michael S. Molina <70410625+michael-s-molina@users.noreply.github.com>
This commit is contained in:
Bruno Motta
2021-04-01 03:08:20 -03:00
committed by GitHub
parent a7f48c6599
commit 1dbc1496b2
2 changed files with 190 additions and 10 deletions

View File

@@ -0,0 +1,181 @@
/**
* 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 { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import * as chartAction from 'src/chart/chartAction';
import * as downloadAsImage from 'src/utils/downloadAsImage';
import fetchMock from 'fetch-mock';
import ConectedDisplayQueryButton from '.';
const createProps = () => ({
latestQueryFormData: {
viz_type: 'histogram',
datasource: '49__table',
slice_id: 318,
url_params: {},
time_range_endpoints: ['inclusive', 'exclusive'],
granularity_sqla: 'time_start',
time_range: 'No filter',
all_columns_x: ['age'],
adhoc_filters: [],
row_limit: 10000,
groupby: null,
color_scheme: 'supersetColors',
label_colors: {},
link_length: '25',
x_axis_label: 'age',
y_axis_label: 'count',
},
slice: {
cache_timeout: null,
changed_on: '2021-03-19T16:30:56.750230',
changed_on_humanized: '3 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">3 days ago</span>',
owners: [],
slice_id: 318,
slice_name: 'Age distribution of respondents',
slice_url: '/superset/explore/?form_data=%7B%22slice_id%22%3A%20318%7D',
},
chartStatus: 'rendered',
onOpenPropertiesModal: jest.fn(),
onOpenInEditor: jest.fn(),
});
fetchMock.post(
'http://api/v1/chart/data?form_data=%7B%22slice_id%22%3A318%7D',
{ body: {} },
{
sendAsJson: false,
},
);
test('Shoud render a button', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, { useRedux: true });
expect(screen.getByRole('button')).toBeInTheDocument();
});
test('Shoud open a menu', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
useRedux: true,
});
expect(props.onOpenInEditor).toBeCalledTimes(0);
expect(props.onOpenPropertiesModal).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(props.onOpenInEditor).toBeCalledTimes(0);
expect(props.onOpenPropertiesModal).toBeCalledTimes(0);
expect(
screen.getByRole('menuitem', { name: 'Edit properties' }),
).toBeInTheDocument();
expect(
screen.getByRole('menuitem', { name: 'View query' }),
).toBeInTheDocument();
expect(
screen.getByRole('menuitem', { name: 'Run in SQL Lab' }),
).toBeInTheDocument();
expect(
screen.getByRole('menuitem', { name: 'Download as image' }),
).toBeInTheDocument();
});
test('Shoud call onOpenPropertiesModal when click on "Edit properties"', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
useRedux: true,
});
expect(props.onOpenInEditor).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
userEvent.click(screen.getByRole('menuitem', { name: 'Edit properties' }));
expect(props.onOpenPropertiesModal).toBeCalledTimes(1);
});
test('Shoud call getChartDataRequest when click on "View query"', async () => {
const props = createProps();
const getChartDataRequest = jest.spyOn(chartAction, 'getChartDataRequest');
render(<ConectedDisplayQueryButton {...props} />, {
useRedux: true,
});
expect(getChartDataRequest).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(getChartDataRequest).toBeCalledTimes(0);
const menuItem = screen.getByText('View query').parentElement!;
userEvent.click(menuItem);
await waitFor(() => expect(getChartDataRequest).toBeCalledTimes(1));
});
test('Shoud call onOpenInEditor when click on "Run in SQL Lab"', () => {
const props = createProps();
render(<ConectedDisplayQueryButton {...props} />, {
useRedux: true,
});
expect(props.onOpenInEditor).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(props.onOpenInEditor).toBeCalledTimes(0);
userEvent.click(screen.getByRole('menuitem', { name: 'Run in SQL Lab' }));
expect(props.onOpenInEditor).toBeCalledTimes(1);
});
test('Shoud call downloadAsImage when click on "Download as image"', () => {
const props = createProps();
const spy = jest.spyOn(downloadAsImage, 'default');
render(<ConectedDisplayQueryButton {...props} />, {
useRedux: true,
});
expect(spy).toBeCalledTimes(0);
userEvent.click(screen.getByRole('button'));
expect(spy).toBeCalledTimes(0);
userEvent.click(screen.getByRole('menuitem', { name: 'Download as image' }));
expect(spy).toBeCalledTimes(1);
});

View File

@@ -0,0 +1,207 @@
/**
* 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 } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import htmlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/htmlbars';
import markdownSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/markdown';
import sqlSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
import jsonSyntax from 'react-syntax-highlighter/dist/cjs/languages/hljs/json';
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import { styled, t } from '@superset-ui/core';
import { Dropdown, Menu } from 'src/common/components';
import { getClientErrorObject } from 'src/utils/getClientErrorObject';
import CopyToClipboard from 'src/components/CopyToClipboard';
import { getChartDataRequest } from 'src/chart/chartAction';
import downloadAsImage from 'src/utils/downloadAsImage';
import Loading from 'src/components/Loading';
import ModalTrigger from 'src/components/ModalTrigger';
import { sliceUpdated } from 'src/explore/actions/exploreActions';
import { CopyButton } from 'src/explore/components/DataTableControl';
SyntaxHighlighter.registerLanguage('markdown', markdownSyntax);
SyntaxHighlighter.registerLanguage('html', htmlSyntax);
SyntaxHighlighter.registerLanguage('sql', sqlSyntax);
SyntaxHighlighter.registerLanguage('json', jsonSyntax);
const propTypes = {
onOpenPropertiesModal: PropTypes.func,
onOpenInEditor: PropTypes.func,
chartStatus: PropTypes.string,
latestQueryFormData: PropTypes.object.isRequired,
slice: PropTypes.object,
};
const MENU_KEYS = {
EDIT_PROPERTIES: 'edit_properties',
RUN_IN_SQL_LAB: 'run_in_sql_lab',
DOWNLOAD_AS_IMAGE: 'download_as_image',
};
const CopyButtonViewQuery = styled(CopyButton)`
&& {
margin: 0 0 ${({ theme }) => theme.gridUnit}px;
}
`;
export const DisplayQueryButton = props => {
const { datasource } = props.latestQueryFormData;
const [language, setLanguage] = useState(null);
const [query, setQuery] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [sqlSupported] = useState(
datasource && datasource.split('__')[1] === 'table',
);
const beforeOpen = resultType => {
setIsLoading(true);
getChartDataRequest({
formData: props.latestQueryFormData,
resultFormat: 'json',
resultType,
})
.then(response => {
// Only displaying the first query is currently supported
const result = response.result[0];
setLanguage(result.language);
setQuery(result.query);
setIsLoading(false);
setError(null);
})
.catch(response => {
getClientErrorObject(response).then(
({ error, message, statusText }) => {
setError(
error || message || statusText || t('Sorry, An error occurred'),
);
setIsLoading(false);
},
);
});
};
const handleMenuClick = ({ key, domEvent }) => {
const { slice, onOpenInEditor, latestQueryFormData } = props;
switch (key) {
case MENU_KEYS.EDIT_PROPERTIES:
props.onOpenPropertiesModal();
break;
case MENU_KEYS.RUN_IN_SQL_LAB:
onOpenInEditor(latestQueryFormData);
break;
case MENU_KEYS.DOWNLOAD_AS_IMAGE:
downloadAsImage(
'.panel-body > .chart-container',
// eslint-disable-next-line camelcase
slice?.slice_name ?? t('New chart'),
{},
true,
)(domEvent);
break;
default:
break;
}
};
const renderQueryModalBody = () => {
if (isLoading) {
return <Loading />;
}
if (error) {
return <pre>{error}</pre>;
}
if (query) {
return (
<div>
<CopyToClipboard
text={query}
shouldShowText={false}
copyNode={
<CopyButtonViewQuery buttonSize="xsmall">
<i className="fa fa-clipboard" />
</CopyButtonViewQuery>
}
/>
<SyntaxHighlighter language={language} style={github}>
{query}
</SyntaxHighlighter>
</div>
);
}
return null;
};
const { slice } = props;
return (
<Dropdown
trigger="click"
data-test="query-dropdown"
overlay={
<Menu onClick={handleMenuClick} selectable={false}>
{slice && (
<Menu.Item key={MENU_KEYS.EDIT_PROPERTIES}>
{t('Edit properties')}
</Menu.Item>
)}
<Menu.Item>
<ModalTrigger
triggerNode={
<span data-test="view-query-menu-item">{t('View query')}</span>
}
modalTitle={t('View query')}
beforeOpen={() => beforeOpen('query')}
modalBody={renderQueryModalBody()}
responsive
/>
</Menu.Item>
{sqlSupported && (
<Menu.Item key={MENU_KEYS.RUN_IN_SQL_LAB}>
{t('Run in SQL Lab')}
</Menu.Item>
)}
<Menu.Item key={MENU_KEYS.DOWNLOAD_AS_IMAGE}>
{t('Download as image')}
</Menu.Item>
</Menu>
}
>
<div
role="button"
id="query"
tabIndex={0}
className="btn btn-default btn-sm"
>
<i role="img" className="fa fa-bars" />
</div>
</Dropdown>
);
};
DisplayQueryButton.propTypes = propTypes;
function mapDispatchToProps(dispatch) {
return bindActionCreators({ sliceUpdated }, dispatch);
}
export default connect(null, mapDispatchToProps)(DisplayQueryButton);