Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Drill to detail Modal tests #21148

Merged
merged 14 commits into from
Aug 29, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions superset-frontend/spec/fixtures/mockChartQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export default {
datasource: datasourceId,
viz_type: 'pie',
slice_id: sliceId,
slice_name: 'Genders',
granularity_sqla: null,
time_grain_sqla: null,
since: '100 years ago',
Expand Down
5 changes: 5 additions & 0 deletions superset-frontend/spec/fixtures/mockState.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ export default {
sliceEntities: sliceEntitiesForChart,
charts: chartQueries,
nativeFilters: nativeFiltersInfo,
common: {
conf: {
SAMPLES_ROW_LIMIT: 10,
},
},
dataMask: mockDataMaskInfo,
dashboardInfo,
dashboardFilters: emptyFilters,
Expand Down
110 changes: 110 additions & 0 deletions superset-frontend/src/components/Chart/DrillDetailModal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* 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 { getMockStoreWithNativeFilters } from 'spec/fixtures/mockStore';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { QueryFormData } from '@superset-ui/core';
import fetchMock from 'fetch-mock';
import userEvent from '@testing-library/user-event';
import DrillDetailModal from './DrillDetailModal';

const chart = chartQueries[sliceId];
const setup = (overrides: Record<string, any> = {}) => {
const store = getMockStoreWithNativeFilters();
const props = {
chartId: sliceId,
initialFilters: [],
formData: chart.form_data as unknown as QueryFormData,
...overrides,
};
return render(<DrillDetailModal {...props} />, {
useRedux: true,
useRouter: true,
store,
});
};
const waitForRender = (overrides: Record<string, any> = {}) =>
waitFor(() => setup(overrides));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it really needed? Don't we always wait for render by default?

Copy link
Member Author

@geido geido Aug 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kgabryje in this component there are several async events that would fire warnings during the test runs if we don't wait for the component to be fully loaded. Hence the reason for this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh that's interesting. Does it mean that we should use this pattern in other components too? Maybe this should be a helper function in spec/helpers?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kgabryje not sure if it is worth creating a function that takes a component and wraps it in a waitFor while also taking eventual overrides but if you think it can help I am happy to create it in a separate PR.

Copy link
Member Author

@geido geido Aug 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general, I think there are a lot of reusable helpers that we can create for these RTL tests. This could be an interesting project in order to enforce/suggest certain standards in writing RTL tests. CC @rusackas

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, approving this PR 👍 Do you think though that other tests would benefit from using this pattern? Should we use it to decrease the number of warnings?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also use findBy in many of these tests if you want to wait for the async operations. findBy is essentially the combination of getBy and waitFor. So this:

test('should render the title', async () => {
  await waitForRender();
  expect(
    screen.getByText(`Drill to detail: ${chart.form_data.slice_name}`),
  ).toBeInTheDocument();
});

Could be written as:

test('should render the title', async () => {
  setup();
  expect(
    await screen.findByText(`Drill to detail: ${chart.form_data.slice_name}`),
  ).toBeInTheDocument();
});

Either way, the important thing is to account for the async nature of the component as you did.


fetchMock.post(
'end:/datasource/samples?force=false&datasource_type=table&datasource_id=7&per_page=50&page=1',
{
result: {
data: [],
colnames: [],
coltypes: [],
},
},
);

const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));

test('should render', async () => {
const { container } = await waitForRender();
expect(container).toBeInTheDocument();
});

test('should render the title', async () => {
await waitForRender();
expect(
screen.getByText(`Drill to detail: ${chart.form_data.slice_name}`),
).toBeInTheDocument();
});

test('should render the modal', async () => {
await waitForRender();
expect(screen.getByRole('dialog')).toBeInTheDocument();
});

test('should not render the modal', async () => {
await waitForRender({
initialFilters: undefined,
});
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

test('should render the button', async () => {
await waitForRender();
expect(
screen.getByRole('button', { name: 'Edit chart' }),
).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Close' })).toHaveLength(2);
});

test('should close the modal', async () => {
await waitForRender();
expect(screen.getByRole('dialog')).toBeInTheDocument();
userEvent.click(screen.getAllByRole('button', { name: 'Close' })[1]);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

test('should forward to Explore', async () => {
await waitForRender();
userEvent.click(screen.getByRole('button', { name: 'Edit chart' }));
expect(mockHistoryPush).toHaveBeenCalledWith(
`/explore/?dashboard_page_id=&slice_id=${sliceId}`,
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/**
* 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 { getMockStoreWithNativeFilters } from 'spec/fixtures/mockStore';
import chartQueries, { sliceId } from 'spec/fixtures/mockChartQueries';
import { QueryFormData, SupersetClient } from '@superset-ui/core';
import fetchMock from 'fetch-mock';
import DrillDetailPane from './DrillDetailPane';

const chart = chartQueries[sliceId];
const setup = (overrides: Record<string, any> = {}) => {
const store = getMockStoreWithNativeFilters();
const props = {
initialFilters: [],
formData: chart.form_data as unknown as QueryFormData,
...overrides,
};
return render(<DrillDetailPane {...props} />, {
useRedux: true,
store,
});
};
const waitForRender = (overrides: Record<string, any> = {}) =>
waitFor(() => setup(overrides));
const samplesEndpoint =
'end:/datasource/samples?force=false&datasource_type=table&datasource_id=7&per_page=50&page=1';
const fetchWithNoData = () =>
fetchMock.post(samplesEndpoint, {
result: {
total_count: 0,
data: [],
colnames: [],
coltypes: [],
},
});
const fetchWithData = () =>
fetchMock.post(samplesEndpoint, {
result: {
total_count: 3,
data: [
{
year: 1996,
na_sales: 11.27,
eu_sales: 8.89,
},
{
year: 1989,
na_sales: 23.2,
eu_sales: 2.26,
},
{
year: 1999,
na_sales: 9,
eu_sales: 6.18,
},
],
colnames: ['year', 'na_sales', 'eu_sales'],
coltypes: [0, 0, 0],
},
});
const SupersetClientPost = jest.spyOn(SupersetClient, 'post');

afterEach(fetchMock.restore);

test('should render', async () => {
fetchWithNoData();
const { container } = await waitForRender();
expect(container).toBeInTheDocument();
});

test('should render the loading component', async () => {
fetchWithData();
setup();
await waitFor(() => {
expect(screen.getByRole('status', { name: 'Loading' })).toBeInTheDocument();
});
});

test('should render the table with results', async () => {
fetchWithData();
await waitForRender();
expect(screen.getByRole('table')).toBeInTheDocument();
expect(screen.getAllByRole('row')).toHaveLength(4);
expect(
screen.getByRole('columnheader', { name: 'year' }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: 'na_sales' }),
).toBeInTheDocument();
expect(
screen.getByRole('columnheader', { name: 'eu_sales' }),
).toBeInTheDocument();
});

test('should render the "No results" components', async () => {
fetchWithNoData();
setup();
expect(
await screen.findByText('No rows were returned for this dataset'),
).toBeInTheDocument();
});

test('should render the error', async () => {
SupersetClientPost.mockRejectedValue(new Error('Something went wrong'));
await waitForRender();
expect(screen.getByText('Error: Something went wrong')).toBeInTheDocument();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* 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 } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import TableControls from './TableControls';

const setFilters = jest.fn();
const onReload = jest.fn();
const setup = (overrides: Record<string, any> = {}) => {
const props = {
filters: [],
setFilters,
onReload,
loading: false,
totalCount: 0,
...overrides,
};
return render(<TableControls {...props} />);
};
test('should render', async () => {
geido marked this conversation as resolved.
Show resolved Hide resolved
const { container } = setup();
expect(container).toBeInTheDocument();
});

test('should show 0 rows', () => {
setup();
expect(screen.getByText('0 rows')).toBeInTheDocument();
});

test('should show the correct amount of rows', () => {
setup({
totalCount: 10,
});
expect(screen.getByText('10 rows')).toBeInTheDocument();
});

test('should render the reload button', () => {
setup();
expect(screen.getByRole('button', { name: 'Reload' })).toBeInTheDocument();
});

test('should show the loading indicator', async () => {
geido marked this conversation as resolved.
Show resolved Hide resolved
setup({
loading: true,
});
expect(screen.getByText('Loading...')).toBeInTheDocument();
});

test('should call onreload', async () => {
geido marked this conversation as resolved.
Show resolved Hide resolved
setup();
userEvent.click(screen.getByRole('button', { name: 'Reload' }));
expect(onReload).toHaveBeenCalledTimes(1);
});

test('should render with filters', async () => {
geido marked this conversation as resolved.
Show resolved Hide resolved
setup({
filters: [
{
col: 'platform',
op: '==',
val: 'GB',
},
{
col: 'lang',
op: '==',
val: 'IT',
},
],
});
expect(screen.getByText('platform')).toBeInTheDocument();
expect(screen.getByText('GB')).toBeInTheDocument();
expect(screen.getByText('lang')).toBeInTheDocument();
expect(screen.getByText('IT')).toBeInTheDocument();
});

test('should remove the filters on close', async () => {
geido marked this conversation as resolved.
Show resolved Hide resolved
setup({
filters: [
{
col: 'platform',
op: '==',
val: 'GB',
},
],
});
expect(screen.getByText('platform')).toBeInTheDocument();
expect(screen.getByText('GB')).toBeInTheDocument();

userEvent.click(screen.getByRole('img', { name: 'close' }));

expect(setFilters).toHaveBeenCalledWith([]);
});
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,23 @@ test('Should "Enter fullscreen"', () => {
userEvent.click(screen.getByText('Enter fullscreen'));
expect(props.handleToggleFullSize).toBeCalledTimes(1);
});

test('Drill to detail modal is under featureflag', () => {
// @ts-ignore
global.featureFlags = {
[FeatureFlag.DRILL_TO_DETAIL]: false,
};
const props = createProps();
renderWrapper(props);
expect(screen.queryByText('Drill to detail')).not.toBeInTheDocument();
});

test('Should show the "Drill to detail"', () => {
// @ts-ignore
global.featureFlags = {
[FeatureFlag.DRILL_TO_DETAIL]: true,
};
const props = createProps();
renderWrapper(props);
expect(screen.getByText('Drill to detail')).toBeInTheDocument();
});