level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
6,851
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/DatabaseErrorMessage.test.tsx
/** * 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 DatabaseErrorMessage from './DatabaseErrorMessage'; import { ErrorLevel, ErrorSource, ErrorTypeEnum } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); const mockedProps = { error: { error_type: ErrorTypeEnum.DATABASE_SECURITY_ACCESS_ERROR, extra: { engine_name: 'Engine name', issue_codes: [ { code: 1, message: 'Issue code message A', }, { code: 2, message: 'Issue code message B', }, ], owners: ['Owner A', 'Owner B'], }, level: 'error' as ErrorLevel, message: 'Error message', }, source: 'dashboard' as ErrorSource, subtitle: 'Error message', }; test('should render', () => { const { container } = render(<DatabaseErrorMessage {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render the error message', () => { render(<DatabaseErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Error message')).toBeInTheDocument(); }); test('should render the issue codes', () => { render(<DatabaseErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText(/This may be triggered by:/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message A/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message B/)).toBeInTheDocument(); }); test('should render the engine name', () => { render(<DatabaseErrorMessage {...mockedProps} />); expect(screen.getByText(/Engine name/)).toBeInTheDocument(); }); test('should render the owners', () => { render(<DatabaseErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect( screen.getByText('Please reach out to the Chart Owners for assistance.'), ).toBeInTheDocument(); expect( screen.getByText('Chart Owners: Owner A, Owner B'), ).toBeInTheDocument(); }); test('should NOT render the owners', () => { const noVisualizationProps = { ...mockedProps, source: 'sqllab' as ErrorSource, }; render(<DatabaseErrorMessage {...noVisualizationProps} />, { useRedux: true, }); const button = screen.getByText('See more'); userEvent.click(button); expect( screen.queryByText('Chart Owners: Owner A, Owner B'), ).not.toBeInTheDocument(); });
6,853
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/DatasetNotFoundErrorMessage.test.tsx
/** * 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 DatasetNotFoundErrorMessage from './DatasetNotFoundErrorMessage'; import { ErrorLevel, ErrorSource, ErrorTypeEnum } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); const mockedProps = { error: { error_type: ErrorTypeEnum.FAILED_FETCHING_DATASOURCE_INFO_ERROR, level: 'error' as ErrorLevel, message: 'The dataset associated with this chart no longer exists', extra: {}, }, source: 'dashboard' as ErrorSource, }; test('should render', () => { const { container } = render( <DatasetNotFoundErrorMessage {...mockedProps} />, ); expect(container).toBeInTheDocument(); }); test('should render the default title', () => { render(<DatasetNotFoundErrorMessage {...mockedProps} />); expect(screen.getByText('Missing dataset')).toBeInTheDocument(); });
6,855
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/ErrorAlert.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import { render, screen } from 'spec/helpers/testing-library'; import { supersetTheme } from '@superset-ui/core'; import { isCurrentUserBot } from 'src/utils/isBot'; import ErrorAlert from './ErrorAlert'; import { ErrorLevel, ErrorSource } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); jest.mock('src/utils/isBot', () => ({ isCurrentUserBot: jest.fn(), })); const mockedProps = { body: 'Error body', level: 'warning' as ErrorLevel, copyText: 'Copy text', subtitle: 'Error subtitle', title: 'Error title', source: 'dashboard' as ErrorSource, description: 'we are unable to connect db.', }; beforeEach(() => { (isCurrentUserBot as jest.Mock).mockReturnValue(false); }); afterEach(() => { jest.clearAllMocks(); }); test('should render', () => { const { container } = render(<ErrorAlert {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render warning icon', () => { render(<ErrorAlert {...mockedProps} />); expect( screen.getByRole('img', { name: 'warning-solid' }), ).toBeInTheDocument(); }); test('should render error icon', () => { const errorProps = { ...mockedProps, level: 'error' as ErrorLevel, }; render(<ErrorAlert {...errorProps} />); expect(screen.getByRole('img', { name: 'error-solid' })).toBeInTheDocument(); }); test('should render the error title', () => { const titleProps = { ...mockedProps, source: 'explore' as ErrorSource, }; render(<ErrorAlert {...titleProps} />); expect(screen.getByText('Error title')).toBeInTheDocument(); }); test('should render the error description', () => { render(<ErrorAlert {...mockedProps} />, { useRedux: true }); expect(screen.getByText('we are unable to connect db.')).toBeInTheDocument(); }); test('should render the error subtitle', () => { render(<ErrorAlert {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Error subtitle')).toBeInTheDocument(); }); test('should render the error body', () => { render(<ErrorAlert {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Error body')).toBeInTheDocument(); }); test('should render the See more button', () => { const seemoreProps = { ...mockedProps, source: 'explore' as ErrorSource, }; render(<ErrorAlert {...seemoreProps} />); expect(screen.getByRole('button')).toBeInTheDocument(); expect(screen.getByText('See more')).toBeInTheDocument(); }); test('should render the error subtitle and body defaultly for the screen capture request', () => { const seemoreProps = { ...mockedProps, source: 'explore' as ErrorSource, }; (isCurrentUserBot as jest.Mock).mockReturnValue(true); render(<ErrorAlert {...seemoreProps} />); expect(screen.getByText('Error subtitle')).toBeInTheDocument(); expect(screen.getByText('Error body')).toBeInTheDocument(); }); test('should render the modal', () => { render(<ErrorAlert {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByRole('dialog')).toBeInTheDocument(); expect(screen.getByText('Close')).toBeInTheDocument(); }); test('should NOT render the modal', () => { const expandableProps = { ...mockedProps, source: 'explore' as ErrorSource, }; render(<ErrorAlert {...expandableProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); test('should render the See less button', () => { const expandableProps = { ...mockedProps, source: 'explore' as ErrorSource, }; render(<ErrorAlert {...expandableProps} />); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('See less')).toBeInTheDocument(); expect(screen.queryByText('See more')).not.toBeInTheDocument(); }); test('should render the Copy button', () => { render(<ErrorAlert {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Copy message')).toBeInTheDocument(); }); test('should render with warning theme', () => { render(<ErrorAlert {...mockedProps} />); expect(screen.getByRole('alert')).toHaveStyle( ` backgroundColor: ${supersetTheme.colors.warning.light2}; `, ); }); test('should render with error theme', () => { const errorProps = { ...mockedProps, level: 'error' as ErrorLevel, }; render(<ErrorAlert {...errorProps} />); expect(screen.getByRole('alert')).toHaveStyle( ` backgroundColor: ${supersetTheme.colors.error.light2}; `, ); });
6,857
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/ErrorMessageWithStackTrace.test.tsx
/** * 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 ErrorMessageWithStackTrace from './ErrorMessageWithStackTrace'; import BasicErrorAlert from './BasicErrorAlert'; import { ErrorLevel, ErrorSource, ErrorTypeEnum } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); const mockedProps = { level: 'warning' as ErrorLevel, link: 'https://sample.com', source: 'dashboard' as ErrorSource, stackTrace: 'Stacktrace', }; test('should render', () => { const { container } = render(<ErrorMessageWithStackTrace {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render the stacktrace', () => { render(<ErrorMessageWithStackTrace {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Stacktrace')).toBeInTheDocument(); }); test('should render the link', () => { render(<ErrorMessageWithStackTrace {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); const link = screen.getByRole('link'); expect(link).toHaveTextContent('(Request Access)'); expect(link).toHaveAttribute('href', mockedProps.link); }); test('should render the fallback', () => { const body = 'Blahblah'; render( <ErrorMessageWithStackTrace error={{ error_type: ErrorTypeEnum.FRONTEND_NETWORK_ERROR, message: body, extra: {}, level: 'error', }} fallback={<BasicErrorAlert title="Blah" body={body} level="error" />} {...mockedProps} />, { useRedux: true }, ); expect(screen.getByText(body)).toBeInTheDocument(); });
6,859
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/IssueCode.test.tsx
/** * 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 IssueCode from './IssueCode'; const mockedProps = { code: 1, message: 'Error message', }; test('should render', () => { const { container } = render(<IssueCode {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render the message', () => { render(<IssueCode {...mockedProps} />); expect(screen.getByText('Error message')).toBeInTheDocument(); }); test('should render the link', () => { render(<IssueCode {...mockedProps} />); const link = screen.getByRole('link'); expect(link).toHaveAttribute( 'href', `https://superset.apache.org/docs/miscellaneous/issue-codes#issue-${mockedProps.code}`, ); });
6,861
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/MarshmallowErrorMessage.test.tsx
/** * 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, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { ThemeProvider, supersetTheme } from '@superset-ui/core'; import { ErrorLevel, ErrorTypeEnum } from 'src/components/ErrorMessage/types'; import MarshmallowErrorMessage from './MarshmallowErrorMessage'; describe('MarshmallowErrorMessage', () => { const mockError = { extra: { messages: { name: ["can't be blank"], age: { inner: ['is too low'], }, }, payload: { name: '', age: { inner: 10, }, }, issue_codes: [], }, message: 'Validation failed', error_type: ErrorTypeEnum.MARSHMALLOW_ERROR, level: 'error' as ErrorLevel, }; test('renders without crashing', () => { render( <ThemeProvider theme={supersetTheme}> <MarshmallowErrorMessage error={mockError} /> </ThemeProvider>, ); expect(screen.getByText('Validation failed')).toBeInTheDocument(); }); test('renders the provided subtitle', () => { render( <ThemeProvider theme={supersetTheme}> <MarshmallowErrorMessage error={mockError} subtitle="Error Alert" /> </ThemeProvider>, ); expect(screen.getByText('Error Alert')).toBeInTheDocument(); }); test('renders extracted invalid values', () => { render( <ThemeProvider theme={supersetTheme}> <MarshmallowErrorMessage error={mockError} /> </ThemeProvider>, ); expect(screen.getByText("can't be blank:")).toBeInTheDocument(); expect(screen.getByText('is too low: 10')).toBeInTheDocument(); }); test('renders the JSONTree when details are expanded', () => { render( <ThemeProvider theme={supersetTheme}> <MarshmallowErrorMessage error={mockError} /> </ThemeProvider>, ); fireEvent.click(screen.getByText('Details')); expect(screen.getByText('"can\'t be blank"')).toBeInTheDocument(); }); });
6,863
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/ParameterErrorMessage.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import ParameterErrorMessage from './ParameterErrorMessage'; import { ErrorLevel, ErrorSource, ErrorTypeEnum } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); const mockedProps = { error: { error_type: ErrorTypeEnum.MISSING_TEMPLATE_PARAMS_ERROR, extra: { template_parameters: { state: 'CA', country: 'ITA' }, undefined_parameters: ['stat', 'count'], issue_codes: [ { code: 1, message: 'Issue code message A', }, { code: 2, message: 'Issue code message B', }, ], }, level: 'error' as ErrorLevel, message: 'Error message', }, source: 'dashboard' as ErrorSource, subtitle: 'Error message', }; test('should render', () => { const { container } = render(<ParameterErrorMessage {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render the default title', () => { render(<ParameterErrorMessage {...mockedProps} />); expect(screen.getByText('Parameter error')).toBeInTheDocument(); }); test('should render the error message', () => { render(<ParameterErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText('Error message')).toBeInTheDocument(); }); test('should render the issue codes', () => { render(<ParameterErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText(/This may be triggered by:/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message A/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message B/)).toBeInTheDocument(); }); test('should render the suggestions', () => { render(<ParameterErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText(/Did you mean:/)).toBeInTheDocument(); expect(screen.getByText('"state" instead of "stat?"')).toBeInTheDocument(); expect(screen.getByText('"country" instead of "count?"')).toBeInTheDocument(); });
6,865
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/TimeoutErrorMessage.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import TimeoutErrorMessage from './TimeoutErrorMessage'; import { ErrorLevel, ErrorSource, ErrorTypeEnum } from './types'; jest.mock( 'src/components/Icons/Icon', () => ({ fileName }: { fileName: string }) => <span role="img" aria-label={fileName.replace('_', '-')} />, ); const mockedProps = { error: { error_type: ErrorTypeEnum.FRONTEND_TIMEOUT_ERROR, extra: { issue_codes: [ { code: 1, message: 'Issue code message A', }, { code: 2, message: 'Issue code message B', }, ], owners: ['Owner A', 'Owner B'], timeout: 30, }, level: 'error' as ErrorLevel, message: 'Error message', }, source: 'dashboard' as ErrorSource, }; test('should render', () => { const { container } = render(<TimeoutErrorMessage {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render the default title', () => { render(<TimeoutErrorMessage {...mockedProps} />); expect(screen.getByText('Timeout error')).toBeInTheDocument(); }); test('should render the issue codes', () => { render(<TimeoutErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect(screen.getByText(/This may be triggered by:/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message A/)).toBeInTheDocument(); expect(screen.getByText(/Issue code message B/)).toBeInTheDocument(); }); test('should render the owners', () => { render(<TimeoutErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect( screen.getByText('Please reach out to the Chart Owners for assistance.'), ).toBeInTheDocument(); expect( screen.getByText('Chart Owners: Owner A, Owner B'), ).toBeInTheDocument(); }); test('should NOT render the owners', () => { const noVisualizationProps = { ...mockedProps, source: 'sqllab' as ErrorSource, }; render(<TimeoutErrorMessage {...noVisualizationProps} />, { useRedux: true, }); const button = screen.getByText('See more'); userEvent.click(button); expect( screen.queryByText('Chart Owners: Owner A, Owner B'), ).not.toBeInTheDocument(); }); test('should render the timeout message', () => { render(<TimeoutErrorMessage {...mockedProps} />, { useRedux: true }); const button = screen.getByText('See more'); userEvent.click(button); expect( screen.getByText( /We’re having trouble loading this visualization. Queries are set to timeout after 30 seconds./, ), ).toBeInTheDocument(); });
6,867
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ErrorMessage/getErrorMessageComponentRegistry.test.tsx
/** * 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 getErrorMessageComponentRegistry from 'src/components/ErrorMessage/getErrorMessageComponentRegistry'; import { ErrorMessageComponentProps } from 'src/components/ErrorMessage/types'; // eslint-disable-next-line @typescript-eslint/no-unused-vars const ERROR_MESSAGE_COMPONENT = (_: ErrorMessageComponentProps) => ( <div>Test error</div> ); // eslint-disable-next-line @typescript-eslint/no-unused-vars const OVERRIDE_ERROR_MESSAGE_COMPONENT = (_: ErrorMessageComponentProps) => ( <div>Custom error</div> ); test('should return undefined for a non existent key', () => { expect(getErrorMessageComponentRegistry().get('INVALID_KEY')).toEqual( undefined, ); }); test('should return a component for a set key', () => { getErrorMessageComponentRegistry().registerValue( 'VALID_KEY', ERROR_MESSAGE_COMPONENT, ); expect(getErrorMessageComponentRegistry().get('VALID_KEY')).toEqual( ERROR_MESSAGE_COMPONENT, ); }); test('should return the correct component for an overridden key', () => { getErrorMessageComponentRegistry().registerValue( 'OVERRIDE_KEY', ERROR_MESSAGE_COMPONENT, ); getErrorMessageComponentRegistry().registerValue( 'OVERRIDE_KEY', OVERRIDE_ERROR_MESSAGE_COMPONENT, ); expect(getErrorMessageComponentRegistry().get('OVERRIDE_KEY')).toEqual( OVERRIDE_ERROR_MESSAGE_COMPONENT, ); });
6,871
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FacePile/FacePile.test.tsx
/** * 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 { styledMount as mount } from 'spec/helpers/theming'; import { Avatar } from 'src/components'; import FacePile from '.'; import { getRandomColor } from './utils'; const users = [...new Array(10)].map((_, i) => ({ first_name: 'user', last_name: `${i}`, id: i, })); describe('FacePile', () => { const wrapper = mount(<FacePile users={users} />); it('is a valid element', () => { expect(wrapper.find(FacePile)).toExist(); }); it('renders an Avatar', () => { expect(wrapper.find(Avatar)).toExist(); }); it('hides overflow', () => { expect(wrapper.find(Avatar).length).toBe(5); }); }); describe('utils', () => { describe('getRandomColor', () => { const colors = ['color1', 'color2', 'color3']; it('produces the same color for the same input values', () => { const name = 'foo'; expect(getRandomColor(name, colors)).toEqual( getRandomColor(name, colors), ); }); it('produces a different color for different input values', () => { expect(getRandomColor('foo', colors)).not.toEqual( getRandomColor('bar', colors), ); }); it('handles non-ascii input values', () => { expect(getRandomColor('泰', colors)).toMatchInlineSnapshot(`"color1"`); expect(getRandomColor('مُحَمَّد‎', colors)).toMatchInlineSnapshot( `"color2"`, ); }); }); });
6,874
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FaveStar/FaveStar.test.tsx
/** * 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 FaveStar from '.'; jest.mock('src/components/Tooltip', () => ({ Tooltip: (props: any) => <div data-test="tooltip" {...props} />, })); test('render right content', async () => { const props = { itemId: 3, saveFaveStar: jest.fn(), }; const { rerender, findByRole } = render(<FaveStar {...props} isStarred />); expect(screen.getByRole('button')).toBeInTheDocument(); expect( screen.getByRole('img', { name: 'favorite-selected' }), ).toBeInTheDocument(); expect(props.saveFaveStar).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(props.saveFaveStar).toBeCalledTimes(1); expect(props.saveFaveStar).toBeCalledWith(props.itemId, true); rerender(<FaveStar {...props} />); expect( await findByRole('img', { name: 'favorite-unselected' }), ).toBeInTheDocument(); expect(props.saveFaveStar).toBeCalledTimes(1); userEvent.click(screen.getByRole('button')); expect(props.saveFaveStar).toBeCalledTimes(2); expect(props.saveFaveStar).toBeCalledWith(props.itemId, false); }); test('render content on tooltip', async () => { const props = { itemId: 3, showTooltip: true, saveFaveStar: jest.fn(), }; render(<FaveStar {...props} />); expect(await screen.findByTestId('tooltip')).toBeInTheDocument(); expect(screen.getByTestId('tooltip')).toHaveAttribute( 'id', 'fave-unfave-tooltip', ); expect(screen.getByTestId('tooltip')).toHaveAttribute( 'title', 'Click to favorite/unfavorite', ); expect(screen.getByRole('button')).toBeInTheDocument(); }); test('Call fetchFaveStar on first render and on itemId change', async () => { const props = { itemId: 3, fetchFaveStar: jest.fn(), saveFaveStar: jest.fn(), isStarred: false, showTooltip: false, }; const { rerender, findByRole } = render(<FaveStar {...props} />); expect( await findByRole('img', { name: 'favorite-unselected' }), ).toBeInTheDocument(); expect(props.fetchFaveStar).toBeCalledTimes(1); expect(props.fetchFaveStar).toBeCalledWith(props.itemId); rerender(<FaveStar {...{ ...props, itemId: 2 }} />); expect(props.fetchFaveStar).toBeCalledTimes(2); });
6,877
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FilterableTable/FilterableTable.test.tsx
/** * 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 FilterableTable from 'src/components/FilterableTable'; import { render, screen, within } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; describe('FilterableTable', () => { const mockedProps = { orderedColumnKeys: ['a', 'b', 'c', 'children'], data: [ { a: 'a1', b: 'b1', c: 'c1', d: 0, children: 0 }, { a: 'a2', b: 'b2', c: 'c2', d: 100, children: 2 }, { a: null, b: 'b3', c: 'c3', d: 50, children: 1 }, ], height: 500, }; it('is valid element', () => { expect(React.isValidElement(<FilterableTable {...mockedProps} />)).toBe( true, ); }); it('renders a grid with 3 Table rows', () => { const { getByRole, getByText } = render( <FilterableTable {...mockedProps} />, ); expect(getByRole('table')).toBeInTheDocument(); mockedProps.data.forEach(({ b: columnBContent }) => { expect(getByText(columnBContent)).toBeInTheDocument(); }); }); it('filters on a string', () => { const props = { ...mockedProps, filterText: 'b1', }; const { getByText, queryByText } = render(<FilterableTable {...props} />); expect(getByText(props.filterText)).toBeInTheDocument(); expect(queryByText('b2')).toBeFalsy(); expect(queryByText('b3')).toBeFalsy(); }); it('filters on a number', () => { const props = { ...mockedProps, filterText: '100', }; const { getByText, queryByText } = render(<FilterableTable {...props} />); expect(getByText('b2')).toBeInTheDocument(); expect(queryByText('b1')).toBeFalsy(); expect(queryByText('b3')).toBeFalsy(); }); }); describe('FilterableTable sorting - RTL', () => { it('sorts strings correctly', () => { const stringProps = { orderedColumnKeys: ['columnA'], data: [ { columnA: 'Bravo' }, { columnA: 'Alpha' }, { columnA: 'Charlie' }, ], height: 500, }; render(<FilterableTable {...stringProps} />); const stringColumn = within(screen.getByRole('table')) .getByText('columnA') .closest('th'); // Antd 4.x Table does not follow the table role structure. Need a hacky selector to point the cell item const gridCells = screen.getByTitle('Bravo').closest('.virtual-grid'); // Original order expect(gridCells?.textContent).toEqual( ['Bravo', 'Alpha', 'Charlie'].join(''), ); if (stringColumn) { // First click to sort ascending userEvent.click(stringColumn); } expect(gridCells?.textContent).toEqual( ['Alpha', 'Bravo', 'Charlie'].join(''), ); if (stringColumn) { // Second click to sort descending userEvent.click(stringColumn); } expect(gridCells?.textContent).toEqual( ['Charlie', 'Bravo', 'Alpha'].join(''), ); if (stringColumn) { // Third click to clear sorting userEvent.click(stringColumn); } expect(gridCells?.textContent).toEqual( ['Bravo', 'Alpha', 'Charlie'].join(''), ); }); it('sorts integers correctly', () => { const integerProps = { orderedColumnKeys: ['columnB'], data: [{ columnB: 21 }, { columnB: 0 }, { columnB: 623 }], height: 500, }; render(<FilterableTable {...integerProps} />); const integerColumn = within(screen.getByRole('table')) .getByText('columnB') .closest('th'); const gridCells = screen.getByTitle('21').closest('.virtual-grid'); // Original order expect(gridCells?.textContent).toEqual(['21', '0', '623'].join('')); // First click to sort ascending if (integerColumn) { userEvent.click(integerColumn); } expect(gridCells?.textContent).toEqual(['0', '21', '623'].join('')); // Second click to sort descending if (integerColumn) { userEvent.click(integerColumn); } expect(gridCells?.textContent).toEqual(['623', '21', '0'].join('')); // Third click to clear sorting if (integerColumn) { userEvent.click(integerColumn); } expect(gridCells?.textContent).toEqual(['21', '0', '623'].join('')); }); it('sorts floating numbers correctly', () => { const floatProps = { orderedColumnKeys: ['columnC'], data: [{ columnC: 45.67 }, { columnC: 1.23 }, { columnC: 89.0000001 }], height: 500, }; render(<FilterableTable {...floatProps} />); const floatColumn = within(screen.getByRole('table')) .getByText('columnC') .closest('th'); const gridCells = screen.getByTitle('45.67').closest('.virtual-grid'); // Original order expect(gridCells?.textContent).toEqual( ['45.67', '1.23', '89.0000001'].join(''), ); // First click to sort ascending if (floatColumn) { userEvent.click(floatColumn); } expect(gridCells?.textContent).toEqual( ['1.23', '45.67', '89.0000001'].join(''), ); // Second click to sort descending if (floatColumn) { userEvent.click(floatColumn); } expect(gridCells?.textContent).toEqual( ['89.0000001', '45.67', '1.23'].join(''), ); // Third click to clear sorting if (floatColumn) { userEvent.click(floatColumn); } expect(gridCells?.textContent).toEqual( ['45.67', '1.23', '89.0000001'].join(''), ); }); it('sorts rows properly when floating numbers have mixed types', () => { const mixedFloatProps = { orderedColumnKeys: ['columnD'], data: [ { columnD: 48710.92 }, { columnD: 145776.56 }, { columnD: 72212.86 }, { columnD: '144729.96000000002' }, { columnD: '26260.210000000003' }, { columnD: '152718.97999999998' }, { columnD: 28550.59 }, { columnD: '24078.610000000004' }, { columnD: '98089.08000000002' }, { columnD: '3439718.0300000007' }, { columnD: '4528047.219999993' }, ], height: 500, }; render(<FilterableTable {...mixedFloatProps} />); const mixedFloatColumn = within(screen.getByRole('table')) .getByText('columnD') .closest('th'); const gridCells = screen.getByTitle('48710.92').closest('.virtual-grid'); // Original order expect(gridCells?.textContent).toEqual( [ '48710.92', '145776.56', '72212.86', '144729.96000000002', '26260.210000000003', '152718.97999999998', '28550.59', '24078.610000000004', '98089.08000000002', '3439718.0300000007', '4528047.219999993', ].join(''), ); // First click to sort ascending if (mixedFloatColumn) { userEvent.click(mixedFloatColumn); } expect(gridCells?.textContent).toEqual( [ '24078.610000000004', '26260.210000000003', '28550.59', '48710.92', '72212.86', '98089.08000000002', '144729.96000000002', '145776.56', '152718.97999999998', '3439718.0300000007', '4528047.219999993', ].join(''), ); // Second click to sort descending if (mixedFloatColumn) { userEvent.click(mixedFloatColumn); } expect(gridCells?.textContent).toEqual( [ '4528047.219999993', '3439718.0300000007', '152718.97999999998', '145776.56', '144729.96000000002', '98089.08000000002', '72212.86', '48710.92', '28550.59', '26260.210000000003', '24078.610000000004', ].join(''), ); // Third click to clear sorting if (mixedFloatColumn) { userEvent.click(mixedFloatColumn); } expect(gridCells?.textContent).toEqual( [ '48710.92', '145776.56', '72212.86', '144729.96000000002', '26260.210000000003', '152718.97999999998', '28550.59', '24078.610000000004', '98089.08000000002', '3439718.0300000007', '4528047.219999993', ].join(''), ); }); it('sorts YYYY-MM-DD properly', () => { const dsProps = { orderedColumnKeys: ['columnDS'], data: [ { columnDS: '2021-01-01' }, { columnDS: '2022-01-01' }, { columnDS: '2021-01-02' }, { columnDS: '2021-01-03' }, { columnDS: '2021-12-01' }, { columnDS: '2021-10-01' }, { columnDS: '2022-01-02' }, ], height: 500, }; render(<FilterableTable {...dsProps} />); const dsColumn = within(screen.getByRole('table')) .getByText('columnDS') .closest('th'); const gridCells = screen.getByTitle('2021-01-01').closest('.virtual-grid'); // Original order expect(gridCells?.textContent).toEqual( [ '2021-01-01', '2022-01-01', '2021-01-02', '2021-01-03', '2021-12-01', '2021-10-01', '2022-01-02', ].join(''), ); // First click to sort ascending if (dsColumn) { userEvent.click(dsColumn); } expect(gridCells?.textContent).toEqual( [ '2021-01-01', '2021-01-02', '2021-01-03', '2021-10-01', '2021-12-01', '2022-01-01', '2022-01-02', ].join(''), ); // Second click to sort descending if (dsColumn) { userEvent.click(dsColumn); } expect(gridCells?.textContent).toEqual( [ '2022-01-02', '2022-01-01', '2021-12-01', '2021-10-01', '2021-01-03', '2021-01-02', '2021-01-01', ].join(''), ); // Third click to clear sorting if (dsColumn) { userEvent.click(dsColumn); } expect(gridCells?.textContent).toEqual( [ '2021-01-01', '2022-01-01', '2021-01-02', '2021-01-03', '2021-12-01', '2021-10-01', '2022-01-02', ].join(''), ); }); });
6,879
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FilterableTable/useCellContentParser.test.ts
/** * 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 { renderHook } from '@testing-library/react-hooks'; import { useCellContentParser } from './useCellContentParser'; test('should return NULL for null cell data', () => { const { result } = renderHook(() => useCellContentParser({ columnKeys: [], expandedColumns: [] }), ); const parser = result.current; expect(parser({ cellData: null, columnKey: '' })).toBe('NULL'); }); test('should return truncated string for complex columns', () => { const { result } = renderHook(() => useCellContentParser({ columnKeys: ['a'], expandedColumns: ['a.b'], }), ); const parser = result.current; expect( parser({ cellData: 'this is a very long string', columnKey: 'a.b', }), ).toBe('this is a very long string'); expect( parser({ cellData: '["this is a very long string"]', columnKey: 'a', }), ).toBe('[…]'); expect( parser({ cellData: '{ "b": "this is a very long string" }', columnKey: 'a', }), ).toBe('{…}'); });
6,881
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FilterableTable/utils.test.tsx
/** * 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 } from 'spec/helpers/testing-library'; import { renderResultCell } from './utils'; jest.mock('src/components/JsonModal', () => ({ ...jest.requireActual('src/components/JsonModal'), default: () => <div data-test="mock-json-modal" />, })); const unexpectedGetCellContent = () => 'none'; test('should render NULL for null cell data', () => { const { container } = render( <> {renderResultCell({ cellData: null, columnKey: 'column1', getCellContent: unexpectedGetCellContent, })} </>, ); expect(container).toHaveTextContent('NULL'); }); test('should render JsonModal for json cell data', () => { const { getByTestId } = render( <> {renderResultCell({ cellData: '{ "a": 1 }', columnKey: 'a', getCellContent: unexpectedGetCellContent, })} </>, ); expect(getByTestId('mock-json-modal')).toBeInTheDocument(); }); test('should render cellData value for default cell data', () => { const { container } = render( <> {renderResultCell({ cellData: 'regular_text', columnKey: 'a', })} </>, ); expect(container).toHaveTextContent('regular_text'); }); test('should transform cell data by getCellContent for the regular text', () => { const { container } = render( <> {renderResultCell({ cellData: 'regular_text', columnKey: 'a', getCellContent: ({ cellData, columnKey }) => `${cellData}:${columnKey}`, })} </>, ); expect(container).toHaveTextContent('regular_text:a'); });
6,883
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/FlashProvider/FlashProvider.test.tsx
/** * 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 { render, screen } from 'spec/helpers/testing-library'; import React from 'react'; import { Provider } from 'react-redux'; import { store } from 'src/views/store'; import FlashProvider, { FlashMessage } from './index'; test('Rerendering correctly with default props', () => { const messages: FlashMessage[] = []; render( <Provider store={store}> <FlashProvider messages={messages}> <div data-test="my-component">My Component</div> </FlashProvider> </Provider>, ); expect(screen.getByTestId('my-component')).toBeInTheDocument(); }); test('messages should only be inserted in the State when the component is mounted', () => { const messages: FlashMessage[] = [ ['info', 'teste message 01'], ['info', 'teste message 02'], ]; expect(store.getState().messageToasts).toEqual([]); const { rerender } = render( <Provider store={store}> <FlashProvider messages={messages}> <div data-teste="my-component">My Component</div> </FlashProvider> </Provider>, ); const fistRender = store.getState().messageToasts; expect(fistRender).toHaveLength(2); expect(fistRender[1].text).toBe(messages[0][1]); expect(fistRender[0].text).toBe(messages[1][1]); rerender( <Provider store={store}> <FlashProvider messages={[...messages, ['info', 'teste message 03']]}> <div data-teste="my-component">My Component</div> </FlashProvider> </Provider>, ); const secondRender = store.getState().messageToasts; expect(secondRender).toEqual(fistRender); });
6,895
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/GenericLink/GenericLink.test.tsx
/** * 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 { GenericLink } from './GenericLink'; test('renders', () => { render(<GenericLink to="/explore">Link to Explore</GenericLink>, { useRouter: true, }); expect(screen.getByText('Link to Explore')).toBeVisible(); }); test('navigates to internal URL', () => { render(<GenericLink to="/explore">Link to Explore</GenericLink>, { useRouter: true, }); const internalLink = screen.getByTestId('internal-link'); expect(internalLink).toHaveAttribute('href', '/explore'); }); test('navigates to external URL', () => { render( <GenericLink to="https://superset.apache.org/"> Link to external website </GenericLink>, { useRouter: true }, ); const externalLink = screen.getByTestId('external-link'); expect(externalLink).toHaveAttribute('href', 'https://superset.apache.org/'); }); test('navigates to external URL without host', () => { render( <GenericLink to="superset.apache.org/"> Link to external website </GenericLink>, { useRouter: true }, ); const externalLink = screen.getByTestId('external-link'); expect(externalLink).toHaveAttribute('href', '//superset.apache.org/'); });
6,909
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ImportModal/ImportModal.test.tsx
/** * 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 { act } from 'react-dom/test-utils'; import thunk from 'redux-thunk'; import configureStore from 'redux-mock-store'; import { styledMount as mount } from 'spec/helpers/theming'; import { ReactWrapper } from 'enzyme'; import fetchMock from 'fetch-mock'; import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint'; import { Upload } from 'src/components'; import Button from 'src/components/Button'; import { ImportResourceName } from 'src/views/CRUD/types'; import ImportModelsModal from 'src/components/ImportModal'; import Modal from 'src/components/Modal'; const mockStore = configureStore([thunk]); const store = mockStore({}); const DATABASE_IMPORT_URL = 'glob:*/api/v1/database/import/'; fetchMock.config.overwriteRoutes = true; fetchMock.post(DATABASE_IMPORT_URL, { result: 'OK' }); const requiredProps = { resourceName: 'database' as ImportResourceName, resourceLabel: 'database', passwordsNeededMessage: 'Passwords are needed', confirmOverwriteMessage: 'Database exists', addDangerToast: () => {}, addSuccessToast: () => {}, onModelImport: () => {}, show: true, onHide: () => {}, }; describe('ImportModelsModal', () => { let wrapper: ReactWrapper; beforeEach(() => { wrapper = mount(<ImportModelsModal {...requiredProps} />, { context: { store }, }); }); afterEach(() => { jest.clearAllMocks(); }); it('renders', () => { expect(wrapper.find(ImportModelsModal)).toExist(); }); it('renders a Modal', () => { expect(wrapper.find(Modal)).toExist(); }); it('renders "Import database" header', () => { expect(wrapper.find('h4').text()).toEqual('Import database'); }); it('renders a file input field', () => { expect(wrapper.find('input[type="file"]')).toExist(); }); it('should render the close, file, import and cancel buttons', () => { expect(wrapper.find('button')).toHaveLength(4); }); it('should render the import button initially disabled', () => { expect(wrapper.find(Button).at(2).prop('disabled')).toBe(true); }); it('should render the import button enabled when a file is selected', () => { const file = new File([new ArrayBuffer(1)], 'model_export.zip'); act(() => { const handler = wrapper.find(Upload).prop('onChange'); if (handler) { handler({ fileList: [], file: { name: 'model_export.zip', originFileObj: file, uid: '-1', size: 0, type: 'zip', }, }); } }); wrapper.update(); expect(wrapper.find(Button).at(2).prop('disabled')).toBe(false); }); it('should POST with request header `Accept: application/json`', async () => { const file = new File([new ArrayBuffer(1)], 'model_export.zip'); act(() => { const handler = wrapper.find(Upload).prop('onChange'); if (handler) { handler({ fileList: [], file: { name: 'model_export.zip', originFileObj: file, uid: '-1', size: 0, type: 'zip', }, }); } }); wrapper.update(); wrapper.find(Button).at(2).simulate('click'); await waitForComponentToPaint(wrapper); expect(fetchMock.calls(DATABASE_IMPORT_URL)[0][1]?.headers).toStrictEqual({ Accept: 'application/json', 'X-CSRFToken': '1234', }); }); it('should render password fields when needed for import', () => { const wrapperWithPasswords = mount( <ImportModelsModal {...requiredProps} passwordFields={['databases/examples.yaml']} />, { context: { store }, }, ); expect(wrapperWithPasswords.find('input[type="password"]')).toExist(); }); it('should render ssh_tunnel password fields when needed for import', () => { const wrapperWithPasswords = mount( <ImportModelsModal {...requiredProps} sshTunnelPasswordFields={['databases/examples.yaml']} />, { context: { store }, }, ); expect( wrapperWithPasswords.find('[data-test="ssh_tunnel_password"]'), ).toExist(); }); it('should render ssh_tunnel private_key fields when needed for import', () => { const wrapperWithPasswords = mount( <ImportModelsModal {...requiredProps} sshTunnelPrivateKeyFields={['databases/examples.yaml']} />, { context: { store }, }, ); expect( wrapperWithPasswords.find('[data-test="ssh_tunnel_private_key"]'), ).toExist(); }); it('should render ssh_tunnel private_key_password fields when needed for import', () => { const wrapperWithPasswords = mount( <ImportModelsModal {...requiredProps} sshTunnelPrivateKeyPasswordFields={['databases/examples.yaml']} />, { context: { store }, }, ); expect( wrapperWithPasswords.find( '[data-test="ssh_tunnel_private_key_password"]', ), ).toExist(); }); });
6,913
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/IndeterminateCheckbox/IndeterminateCheckbox.test.tsx
/** * 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 IndeterminateCheckbox, { IndeterminateCheckboxProps } from '.'; const mockedProps: IndeterminateCheckboxProps = { checked: false, id: 'checkbox-id', indeterminate: false, title: 'Checkbox title', onChange: jest.fn(), }; const asyncRender = (props = mockedProps) => waitFor(() => render(<IndeterminateCheckbox {...props} />)); test('should render', async () => { const { container } = await asyncRender(); expect(container).toBeInTheDocument(); }); test('should render the label', async () => { await asyncRender(); expect(screen.getByTitle('Checkbox title')).toBeInTheDocument(); }); test('should render the checkbox', async () => { await asyncRender(); expect(screen.getByRole('checkbox')).toBeInTheDocument(); }); test('should render the checkbox-half icon', async () => { const indeterminateProps = { ...mockedProps, indeterminate: true, }; await asyncRender(indeterminateProps); expect(screen.getByRole('img')).toBeInTheDocument(); expect(screen.getByRole('img')).toHaveAttribute( 'aria-label', 'checkbox-half', ); }); test('should render the checkbox-off icon', async () => { await asyncRender(); expect(screen.getByRole('img')).toBeInTheDocument(); expect(screen.getByRole('img')).toHaveAttribute('aria-label', 'checkbox-off'); }); test('should render the checkbox-on icon', async () => { const checkboxOnProps = { ...mockedProps, checked: true, }; await asyncRender(checkboxOnProps); expect(screen.getByRole('img')).toBeInTheDocument(); expect(screen.getByRole('img')).toHaveAttribute('aria-label', 'checkbox-on'); }); test('should call the onChange', async () => { await asyncRender(); const label = screen.getByTitle('Checkbox title'); userEvent.click(label); expect(mockedProps.onChange).toHaveBeenCalledTimes(1); });
6,918
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/JsonModal/JsonModal.test.tsx
/** * 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 { fireEvent, render } from 'spec/helpers/testing-library'; import JsonModal, { convertBigIntStrToNumber } from '.'; jest.mock('react-json-tree', () => ({ JSONTree: () => <div data-test="mock-json-tree" />, })); test('renders JSON object in a tree view in a modal', () => { const jsonData = { a: 1 }; const jsonValue = JSON.stringify(jsonData); const { getByText, getByTestId, queryByTestId } = render( <JsonModal jsonObject={jsonData} jsonValue={jsonValue} modalTitle="title" />, { useRedux: true, }, ); expect(queryByTestId('mock-json-tree')).not.toBeInTheDocument(); const link = getByText(jsonValue); fireEvent.click(link); expect(getByTestId('mock-json-tree')).toBeInTheDocument(); }); test('renders bigInt value in a number format', () => { expect(convertBigIntStrToNumber('123')).toBe('123'); expect(convertBigIntStrToNumber('some string value')).toBe( 'some string value', ); expect(convertBigIntStrToNumber('{ a: 123 }')).toBe('{ a: 123 }'); expect(convertBigIntStrToNumber('"Not a Number"')).toBe('"Not a Number"'); // trim quotes for bigint string format expect(convertBigIntStrToNumber('"-12345678901234567890"')).toBe( '-12345678901234567890', ); expect(convertBigIntStrToNumber('"12345678901234567890"')).toBe( '12345678901234567890', ); });
6,921
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Label/Label.test.tsx
/** * 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 { ReactWrapper } from 'enzyme'; import { styledMount as mount } from 'spec/helpers/theming'; import Label from '.'; import { LabelGallery, options } from './Label.stories'; describe('Label', () => { let wrapper: ReactWrapper; // test the basic component it('renders the base component (no onClick)', () => { expect(React.isValidElement(<Label />)).toBe(true); }); it('works with an onClick handler', () => { const mockAction = jest.fn(); wrapper = mount(<Label onClick={mockAction} />); wrapper.find(Label).simulate('click'); expect(mockAction).toHaveBeenCalled(); }); // test stories from the storybook! it('renders all the storybook gallery variants', () => { wrapper = mount(<LabelGallery />); expect(wrapper.find(Label).length).toEqual(options.length * 2); }); });
6,923
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/LastUpdated/LastUpdated.test.tsx
/** * 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 { ReactWrapper } from 'enzyme'; import { styledMount as mount } from 'spec/helpers/theming'; import waitForComponentToPaint from 'spec/helpers/waitForComponentToPaint'; import LastUpdated from '.'; describe('LastUpdated', () => { let wrapper: ReactWrapper; const updatedAt = new Date('Sat Dec 12 2020 00:00:00 GMT-0800'); it('renders the base component (no refresh)', () => { const wrapper = mount(<LastUpdated updatedAt={updatedAt} />); expect(/^Last Updated .+$/.test(wrapper.text())).toBe(true); }); it('renders a refresh action', async () => { const mockAction = jest.fn(); wrapper = mount(<LastUpdated updatedAt={updatedAt} update={mockAction} />); await waitForComponentToPaint(wrapper); const props = wrapper.find('[aria-label="refresh"]').first().props(); if (props.onClick) { props.onClick({} as React.MouseEvent); } expect(mockAction).toHaveBeenCalled(); }); });
6,928
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ListView/CrossLinks.test.tsx
/** * 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 CrossLinks, { CrossLinksProps } from './CrossLinks'; const mockedProps = { crossLinks: [ { id: 1, title: 'Test dashboard', }, { id: 2, title: 'Test dashboard 2', }, { id: 3, title: 'Test dashboard 3', }, { id: 4, title: 'Test dashboard 4', }, ], }; function setup(overrideProps: CrossLinksProps | {} = {}) { return render(<CrossLinks {...mockedProps} {...overrideProps} />, { useRouter: true, }); } test('should render', () => { const { container } = setup(); expect(container).toBeInTheDocument(); }); test('should not render links', () => { setup({ crossLinks: [], }); expect(screen.queryByRole('link')).not.toBeInTheDocument(); }); test('should render the link with just one item', () => { setup({ crossLinks: [ { id: 1, title: 'Test dashboard', }, ], }); expect(screen.getByText('Test dashboard')).toBeInTheDocument(); expect(screen.getByRole('link')).toHaveAttribute( 'href', `/superset/dashboard/1`, ); }); test('should render a custom prefix link', () => { setup({ crossLinks: [ { id: 1, title: 'Test dashboard', }, ], linkPrefix: '/custom/dashboard/', }); expect(screen.getByRole('link')).toHaveAttribute( 'href', `/custom/dashboard/1`, ); }); test('should render multiple links', () => { setup(); expect(screen.getAllByRole('link')).toHaveLength(4); });
6,930
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ListView/CrossLinksTooltip.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import CrossLinksTooltip, { CrossLinksTooltipProps } from './CrossLinksTooltip'; const mockedProps = { crossLinks: [ { to: 'somewhere/1', title: 'Test dashboard', }, { to: 'somewhere/2', title: 'Test dashboard 2', }, { to: 'somewhere/3', title: 'Test dashboard 3', }, { to: 'somewhere/4', title: 'Test dashboard 4', }, ], moreItems: 0, show: true, }; function setup(overrideProps: CrossLinksTooltipProps | {} = {}) { return render( <CrossLinksTooltip {...mockedProps} {...overrideProps}> Hover me </CrossLinksTooltip>, { useRouter: true, }, ); } test('should render', () => { const { container } = setup(); expect(container).toBeInTheDocument(); }); test('should render multiple links', async () => { setup(); userEvent.hover(screen.getByText('Hover me')); await waitFor(() => { expect(screen.getByText('Test dashboard')).toBeInTheDocument(); expect(screen.getByText('Test dashboard 2')).toBeInTheDocument(); expect(screen.getByText('Test dashboard 3')).toBeInTheDocument(); expect(screen.getByText('Test dashboard 4')).toBeInTheDocument(); expect(screen.getAllByRole('link')).toHaveLength(4); }); }); test('should not render the "+ {x} more"', () => { setup(); userEvent.hover(screen.getByText('Hover me')); expect(screen.queryByTestId('plus-more')).not.toBeInTheDocument(); }); test('should render the "+ {x} more"', async () => { setup({ moreItems: 3, }); userEvent.hover(screen.getByText('Hover me')); expect(await screen.findByTestId('plus-more')).toBeInTheDocument(); expect(await screen.findByText('+ 3 more')).toBeInTheDocument(); });
6,948
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Loading/Loading.test.tsx
/** * 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 '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react'; import Loading from './index'; test('Rerendering correctly with default props', () => { render(<Loading />); const loading = screen.getByRole('status'); const classNames = loading.getAttribute('class')?.split(' '); const ariaLive = loading.getAttribute('aria-live'); const ariaLabel = loading.getAttribute('aria-label'); expect(loading).toBeInTheDocument(); expect(classNames).toContain('floating'); expect(classNames).toContain('loading'); expect(ariaLive).toContain('polite'); expect(ariaLabel).toContain('Loading'); }); test('Position must be a class', () => { render(<Loading position="normal" />); const loading = screen.getByRole('status'); const classNames = loading.getAttribute('class')?.split(' '); expect(loading).toBeInTheDocument(); expect(classNames).not.toContain('floating'); expect(classNames).toContain('normal'); }); test('support for extra classes', () => { render(<Loading className="extra-class" />); const loading = screen.getByRole('status'); const classNames = loading.getAttribute('class')?.split(' '); expect(loading).toBeInTheDocument(); expect(classNames).toContain('loading'); expect(classNames).toContain('floating'); expect(classNames).toContain('extra-class'); }); test('Different image path', () => { render(<Loading image="/src/assets/images/loading.gif" />); const loading = screen.getByRole('status'); const imagePath = loading.getAttribute('src'); expect(loading).toBeInTheDocument(); expect(imagePath).toBe('/src/assets/images/loading.gif'); });
6,968
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/MetadataBar/MetadataBar.test.tsx
/** * 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, within } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import * as resizeDetector from 'react-resize-detector'; import { supersetTheme, hexToRgb } from '@superset-ui/core'; import MetadataBar, { MIN_NUMBER_ITEMS, MAX_NUMBER_ITEMS, ContentType, MetadataType, } from '.'; const DASHBOARD_TITLE = 'Added to 452 dashboards'; const DASHBOARD_DESCRIPTION = 'To preview the list of dashboards go to "More" settings on the right.'; const DESCRIPTION_VALUE = 'This is the description'; const ROWS_TITLE = '500 rows'; const SQL_TITLE = 'Click to view query'; const TABLE_TITLE = 'database.schema.table'; const CREATED_BY = 'Jane Smith'; const MODIFIED_BY = 'Jane Smith'; const OWNERS = ['John Doe', 'Mary Wilson']; const TAGS = ['management', 'research', 'poc']; const A_WEEK_AGO = 'a week ago'; const TWO_DAYS_AGO = '2 days ago'; const runWithBarCollapsed = async (func: Function) => { const spy = jest.spyOn(resizeDetector, 'useResizeDetector'); let width: number; spy.mockImplementation(props => { if (props?.onResize && !width) { width = 80; props.onResize(width); } return { ref: { current: undefined } }; }); await func(); spy.mockRestore(); }; const ITEMS: ContentType[] = [ { type: MetadataType.DASHBOARDS, title: DASHBOARD_TITLE, description: DASHBOARD_DESCRIPTION, }, { type: MetadataType.DESCRIPTION, value: DESCRIPTION_VALUE, }, { type: MetadataType.LAST_MODIFIED, value: TWO_DAYS_AGO, modifiedBy: MODIFIED_BY, }, { type: MetadataType.OWNER, createdBy: CREATED_BY, owners: OWNERS, createdOn: A_WEEK_AGO, }, { type: MetadataType.ROWS, title: ROWS_TITLE, }, { type: MetadataType.SQL, title: SQL_TITLE, }, { type: MetadataType.TABLE, title: TABLE_TITLE, }, { type: MetadataType.TAGS, values: TAGS, }, ]; test('renders an array of items', () => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); expect(screen.getByText(DASHBOARD_TITLE)).toBeInTheDocument(); expect(screen.getByText(DESCRIPTION_VALUE)).toBeInTheDocument(); }); test('throws errors when out of min/max restrictions', () => { const spy = jest.spyOn(console, 'error'); spy.mockImplementation(() => {}); expect(() => render(<MetadataBar items={ITEMS.slice(0, MIN_NUMBER_ITEMS - 1)} />), ).toThrow( `The minimum number of items for the metadata bar is ${MIN_NUMBER_ITEMS}.`, ); expect(() => render(<MetadataBar items={ITEMS.slice(0, MAX_NUMBER_ITEMS + 1)} />), ).toThrow( `The maximum number of items for the metadata bar is ${MAX_NUMBER_ITEMS}.`, ); spy.mockRestore(); }); test('removes duplicated items when rendering', () => { render(<MetadataBar items={[...ITEMS.slice(0, 2), ...ITEMS.slice(0, 2)]} />); expect(screen.getAllByRole('img').length).toBe(2); }); test('collapses the bar when min width is reached', async () => { await runWithBarCollapsed(() => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); expect(screen.queryByText(DASHBOARD_TITLE)).not.toBeInTheDocument(); expect(screen.queryByText(DESCRIPTION_VALUE)).not.toBeInTheDocument(); expect(screen.getAllByRole('img').length).toBe(2); }); }); test('always renders a tooltip when the bar is collapsed', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); userEvent.hover(screen.getAllByRole('img')[0]); expect(await screen.findByText(DASHBOARD_DESCRIPTION)).toBeInTheDocument(); userEvent.hover(screen.getAllByRole('img')[1]); expect(await screen.findByText(DESCRIPTION_VALUE)).toBeInTheDocument(); }); }); test('renders a tooltip when one is provided even if not collapsed', async () => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); expect(screen.getByText(DASHBOARD_TITLE)).toBeInTheDocument(); userEvent.hover(screen.getAllByRole('img')[0]); expect(await screen.findByText(DASHBOARD_DESCRIPTION)).toBeInTheDocument(); }); test('renders underlined text and emits event when clickable', () => { const onClick = jest.fn(); const items = [{ ...ITEMS[0], onClick }, ITEMS[1]]; render(<MetadataBar items={items} />); const element = screen.getByText(DASHBOARD_TITLE); userEvent.click(element); expect(onClick).toHaveBeenCalled(); const style = window.getComputedStyle(element); expect(style.textDecoration).toBe('underline'); }); test('renders clicable items with blue icons when the bar is collapsed', async () => { await runWithBarCollapsed(async () => { const onClick = jest.fn(); const items = [{ ...ITEMS[0], onClick }, ITEMS[1]]; render(<MetadataBar items={items} />); const images = screen.getAllByRole('img'); const clickableColor = window.getComputedStyle(images[0]).color; const nonClickableColor = window.getComputedStyle(images[1]).color; expect(clickableColor).toBe(hexToRgb(supersetTheme.colors.primary.base)); expect(nonClickableColor).toBe( hexToRgb(supersetTheme.colors.grayscale.base), ); }); }); test('renders the items sorted', () => { const { container } = render(<MetadataBar items={ITEMS.slice(0, 6)} />); const nodes = container.firstChild?.childNodes as NodeListOf<HTMLElement>; expect(within(nodes[0]).getByText(DASHBOARD_TITLE)).toBeInTheDocument(); expect(within(nodes[1]).getByText(SQL_TITLE)).toBeInTheDocument(); expect(within(nodes[2]).getByText(ROWS_TITLE)).toBeInTheDocument(); expect(within(nodes[3]).getByText(DESCRIPTION_VALUE)).toBeInTheDocument(); expect(within(nodes[4]).getByText(CREATED_BY)).toBeInTheDocument(); }); test('correctly renders the dashboards tooltip', async () => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); userEvent.hover(screen.getByText(DASHBOARD_TITLE)); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(DASHBOARD_TITLE)).toBeInTheDocument(); expect(within(tooltip).getByText(DASHBOARD_DESCRIPTION)).toBeInTheDocument(); }); test('correctly renders the description tooltip', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(0, 2)} />); userEvent.hover(screen.getAllByRole('img')[1]); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(DESCRIPTION_VALUE)).toBeInTheDocument(); }); }); test('correctly renders the last modified tooltip', async () => { render(<MetadataBar items={ITEMS.slice(0, 3)} />); userEvent.hover(screen.getByText(TWO_DAYS_AGO)); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(TWO_DAYS_AGO)).toBeInTheDocument(); expect(within(tooltip).getByText(MODIFIED_BY)).toBeInTheDocument(); }); test('correctly renders the owner tooltip', async () => { render(<MetadataBar items={ITEMS.slice(0, 4)} />); userEvent.hover(screen.getByText(CREATED_BY)); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(CREATED_BY)).toBeInTheDocument(); expect(within(tooltip).getByText(A_WEEK_AGO)).toBeInTheDocument(); OWNERS.forEach(owner => expect(within(tooltip).getByText(owner)).toBeInTheDocument(), ); }); test('correctly renders the rows tooltip', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(4, 8)} />); userEvent.hover(screen.getAllByRole('img')[2]); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(ROWS_TITLE)).toBeInTheDocument(); }); }); test('correctly renders the sql tooltip', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(4, 8)} />); userEvent.hover(screen.getAllByRole('img')[1]); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(SQL_TITLE)).toBeInTheDocument(); }); }); test('correctly renders the table tooltip', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(4, 8)} />); userEvent.hover(screen.getAllByRole('img')[0]); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(within(tooltip).getByText(TABLE_TITLE)).toBeInTheDocument(); }); }); test('correctly renders the tags tooltip', async () => { await runWithBarCollapsed(async () => { render(<MetadataBar items={ITEMS.slice(4, 8)} />); userEvent.hover(screen.getAllByRole('img')[3]); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); TAGS.forEach(tag => expect(within(tooltip).getByText(tag)).toBeInTheDocument(), ); }); });
6,975
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ModalTrigger/ModalTrigger.test.tsx
/** * 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 { supersetTheme } from '@superset-ui/core'; import ModalTrigger from '.'; const mockedProps = { triggerNode: <span>Trigger</span>, }; test('should render', () => { const { container } = render(<ModalTrigger {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render a button', () => { render(<ModalTrigger {...mockedProps} />); expect(screen.getByRole('button')).toBeInTheDocument(); }); test('should render a span element by default', () => { render(<ModalTrigger {...mockedProps} />); expect(screen.getByTestId('span-modal-trigger')).toBeInTheDocument(); }); test('should render a button element when specified', () => { const btnProps = { ...mockedProps, isButton: true, }; render(<ModalTrigger {...btnProps} />); expect(screen.getByTestId('btn-modal-trigger')).toBeInTheDocument(); }); test('should render triggerNode', () => { render(<ModalTrigger {...mockedProps} />); expect(screen.getByText('Trigger')).toBeInTheDocument(); }); test('should render a tooltip on hover', async () => { const tooltipProps = { ...mockedProps, isButton: true, tooltip: 'I am a tooltip', }; render(<ModalTrigger {...tooltipProps} />); userEvent.hover(screen.getByRole('button')); await waitFor(() => expect(screen.getByRole('tooltip')).toBeInTheDocument()); }); test('should not render a modal before click', () => { render(<ModalTrigger {...mockedProps} />); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); test('should render a modal after click', () => { render(<ModalTrigger {...mockedProps} />); userEvent.click(screen.getByRole('button')); expect(screen.getByRole('dialog')).toBeInTheDocument(); }); test('renders with theme', () => { const btnProps = { ...mockedProps, isButton: true, }; render(<ModalTrigger {...btnProps} />); const button = screen.getByRole('button'); expect(button.firstChild).toHaveStyle(` fontSize: ${supersetTheme.typography.sizes.s}; `); });
6,977
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/PageHeaderWithActions/PageHeaderWithActions.test.tsx
/** * 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 { PageHeaderWithActions, PageHeaderWithActionsProps } from './index'; import { Menu } from '../Menu'; const defaultProps: PageHeaderWithActionsProps = { editableTitleProps: { title: 'Test title', placeholder: 'Test placeholder', onSave: jest.fn(), canEdit: true, label: 'Title', }, showTitlePanelItems: true, certificatiedBadgeProps: {}, showFaveStar: true, faveStarProps: { itemId: 1, saveFaveStar: jest.fn() }, titlePanelAdditionalItems: <button type="button">Title panel button</button>, rightPanelAdditionalItems: <button type="button">Save</button>, additionalActionsMenu: ( <Menu> <Menu.Item>Test menu item</Menu.Item> </Menu> ), menuDropdownProps: { onVisibleChange: jest.fn(), visible: true }, }; test('Renders', async () => { render(<PageHeaderWithActions {...defaultProps} />); expect(screen.getByText('Test title')).toBeVisible(); expect(screen.getByTestId('fave-unfave-icon')).toBeVisible(); expect(screen.getByText('Title panel button')).toBeVisible(); expect(screen.getByText('Save')).toBeVisible(); userEvent.click(screen.getByLabelText('Menu actions trigger')); expect(defaultProps.menuDropdownProps.onVisibleChange).toHaveBeenCalled(); });
6,979
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Pagination/Ellipsis.test.tsx
/** * 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 { Ellipsis } from './Ellipsis'; test('Ellipsis - click when the button is enabled', () => { const click = jest.fn(); render(<Ellipsis onClick={click} />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(1); }); test('Ellipsis - click when the button is disabled', () => { const click = jest.fn(); render(<Ellipsis onClick={click} disabled />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(0); });
6,981
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Pagination/Item.test.tsx
/** * 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 { Item } from './Item'; test('Item - click when the item is not active', () => { const click = jest.fn(); render( <Item onClick={click}> <div data-test="test" /> </Item>, ); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(1); expect(screen.getByTestId('test')).toBeInTheDocument(); }); test('Item - click when the item is active', () => { const click = jest.fn(); render( <Item onClick={click} active> <div data-test="test" /> </Item>, ); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(0); expect(screen.getByTestId('test')).toBeInTheDocument(); });
6,983
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Pagination/Next.test.tsx
/** * 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 { Next } from './Next'; test('Next - click when the button is enabled', () => { const click = jest.fn(); render(<Next onClick={click} />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(1); }); test('Next - click when the button is disabled', () => { const click = jest.fn(); render(<Next onClick={click} disabled />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(0); });
6,985
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Pagination/Prev.test.tsx
/** * 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 { Prev } from './Prev'; test('Prev - click when the button is enabled', () => { const click = jest.fn(); render(<Prev onClick={click} />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(1); }); test('Prev - click when the button is disabled', () => { const click = jest.fn(); render(<Prev onClick={click} disabled />); expect(click).toBeCalledTimes(0); userEvent.click(screen.getByRole('button')); expect(click).toBeCalledTimes(0); });
6,987
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Pagination/Wrapper.test.tsx
/** * 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 Wrapper from './Wrapper'; jest.mock('./Next', () => ({ Next: () => <div data-test="next" />, })); jest.mock('./Prev', () => ({ Prev: () => <div data-test="prev" />, })); jest.mock('./Item', () => ({ Item: () => <div data-test="item" />, })); jest.mock('./Ellipsis', () => ({ Ellipsis: () => <div data-test="ellipsis" />, })); test('Pagination rendering correctly', () => { render( <Wrapper> <li data-test="test" /> </Wrapper>, ); expect(screen.getByRole('navigation')).toBeInTheDocument(); expect(screen.getByTestId('test')).toBeInTheDocument(); }); test('Next attribute', () => { render(<Wrapper.Next onClick={jest.fn()} />); expect(screen.getByTestId('next')).toBeInTheDocument(); }); test('Prev attribute', () => { render(<Wrapper.Next onClick={jest.fn()} />); expect(screen.getByTestId('next')).toBeInTheDocument(); }); test('Item attribute', () => { render( <Wrapper.Item onClick={jest.fn()}> <></> </Wrapper.Item>, ); expect(screen.getByTestId('item')).toBeInTheDocument(); }); test('Ellipsis attribute', () => { render(<Wrapper.Ellipsis onClick={jest.fn()} />); expect(screen.getByTestId('ellipsis')).toBeInTheDocument(); });
6,992
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Popover/Popover.test.tsx
/** * 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 { supersetTheme } from '@superset-ui/core'; import Icons from 'src/components/Icons'; import Button from 'src/components/Button'; import Popover from '.'; test('should render', () => { const { container } = render(<Popover />); expect(container).toBeInTheDocument(); }); test('should render a title when visible', () => { render(<Popover title="Popover title" visible />); expect(screen.getByText('Popover title')).toBeTruthy(); }); test('should render some content when visible', () => { render(<Popover content="Content sample" visible />); expect(screen.getByText('Content sample')).toBeTruthy(); }); test('it should not render a title or content when not visible', () => { render(<Popover content="Content sample" title="Popover title" />); const content = screen.queryByText('Content sample'); const title = screen.queryByText('Popover title'); expect(content).not.toBeInTheDocument(); expect(title).not.toBeInTheDocument(); }); test('it should render content when not visible but forceRender=true', () => { render(<Popover content="Content sample" forceRender />); expect(screen.getByText('Content sample')).toBeInTheDocument(); }); test('renders with icon child', async () => { render( <Popover content="Content sample" title="Popover title"> <Icons.Alert>Click me</Icons.Alert> </Popover>, ); expect(await screen.findByRole('img')).toBeInTheDocument(); }); test('fires an event when visibility is changed', async () => { const onVisibleChange = jest.fn(); render( <Popover content="Content sample" title="Popover title" onVisibleChange={onVisibleChange} > <Button>Hover me</Button> </Popover>, ); userEvent.hover(screen.getByRole('button')); await waitFor(() => expect(onVisibleChange).toHaveBeenCalledTimes(1)); }); test('renders with theme', () => { render(<Popover content="Content sample" title="Popover title" visible />); const title = screen.getByText('Popover title'); expect(title).toHaveStyle({ fontSize: supersetTheme.gridUnit * 3.5, }); });
6,996
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/PopoverDropdown/PopoverDropdown.test.tsx
/** * 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 PopoverDropdown, { PopoverDropdownProps, OptionProps, } from 'src/components/PopoverDropdown'; const defaultProps: PopoverDropdownProps = { id: 'popover-dropdown', options: [ { label: 'Option 1', value: '1' }, { label: 'Option 2', value: '2' }, ], value: '1', renderButton: (option: OptionProps) => <span>{option.label}</span>, renderOption: (option: OptionProps) => <div>{option.label}</div>, onChange: jest.fn(), }; test('renders with default props', async () => { render(<PopoverDropdown {...defaultProps} />); expect(await screen.findByRole('button')).toBeInTheDocument(); expect(screen.getByRole('button')).toHaveTextContent('Option 1'); }); test('renders the menu on click', async () => { render(<PopoverDropdown {...defaultProps} />); userEvent.click(screen.getByRole('button')); expect(await screen.findByRole('menu')).toBeInTheDocument(); }); test('renders with custom button', async () => { render( <PopoverDropdown {...defaultProps} renderButton={({ label, value }: OptionProps) => ( <button type="button" key={value}> {`Custom ${label}`} </button> )} />, ); expect(await screen.findByText('Custom Option 1')).toBeInTheDocument(); }); test('renders with custom option', async () => { render( <PopoverDropdown {...defaultProps} renderOption={({ label, value }: OptionProps) => ( <button type="button" key={value}> {`Custom ${label}`} </button> )} />, ); userEvent.click(screen.getByRole('button')); expect(await screen.findByText('Custom Option 1')).toBeInTheDocument(); }); test('triggers onChange', async () => { render(<PopoverDropdown {...defaultProps} />); userEvent.click(screen.getByRole('button')); expect(await screen.findByText('Option 2')).toBeInTheDocument(); userEvent.click(screen.getByText('Option 2')); expect(defaultProps.onChange).toHaveBeenCalled(); });
6,999
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/PopoverSection/PopoverSection.test.tsx
/** * 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 PopoverSection from 'src/components/PopoverSection'; test('renders with default props', async () => { render( <PopoverSection title="Title"> <div role="form" /> </PopoverSection>, ); expect(await screen.findByRole('form')).toBeInTheDocument(); expect((await screen.findAllByRole('img')).length).toBe(1); }); test('renders tooltip icon', async () => { render( <PopoverSection title="Title" info="Tooltip"> <div role="form" /> </PopoverSection>, ); expect((await screen.findAllByRole('img')).length).toBe(2); }); test('renders a tooltip when hovered', async () => { render( <PopoverSection title="Title" info="Tooltip"> <div role="form" /> </PopoverSection>, ); userEvent.hover(screen.getAllByRole('img')[0]); expect(await screen.findByRole('tooltip')).toBeInTheDocument(); }); test('calls onSelect when clicked', async () => { const onSelect = jest.fn(); render( <PopoverSection title="Title" onSelect={onSelect}> <div role="form" /> </PopoverSection>, ); userEvent.click(await screen.findByRole('img')); expect(onSelect).toHaveBeenCalled(); });
7,002
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ProgressBar/ProgressBar.test.tsx
/** * 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 ProgressBar, { ProgressBarProps } from '.'; const mockedProps: ProgressBarProps = { percent: 90, }; test('should render', () => { const { container } = render(<ProgressBar {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render with info', () => { render(<ProgressBar {...mockedProps} />); expect(screen.getByText('90%')).toBeInTheDocument(); }); test('should render without info', () => { const noInfoProps = { ...mockedProps, showInfo: false, }; render(<ProgressBar {...noInfoProps} />); expect(screen.queryByText('90%')).not.toBeInTheDocument(); }); test('should render with error icon', () => { const errorProps = { ...mockedProps, status: 'exception' as const, }; render(<ProgressBar {...errorProps} />); expect(screen.getByLabelText('close-circle')).toBeInTheDocument(); }); test('should render with success icon', () => { const successProps = { ...mockedProps, status: 'success' as const, }; render(<ProgressBar {...successProps} />); expect(screen.getByLabelText('check-circle')).toBeInTheDocument(); }); test('should render with stripes', () => { const stripedProps = { ...mockedProps, striped: true, }; const { container } = render(<ProgressBar {...stripedProps} />); expect(container).toHaveStyle( `background-image: 'linear-gradient( 45deg,rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent) !important'`, ); });
7,007
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/RefreshLabel/RefreshLabel.test.tsx
/** * 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 RefreshLabel from 'src/components/RefreshLabel'; test('renders with default props', async () => { render(<RefreshLabel tooltipContent="Tooltip" onClick={jest.fn()} />); const refresh = await screen.findByRole('button'); expect(refresh).toBeInTheDocument(); userEvent.hover(refresh); }); test('renders tooltip on hover', async () => { const tooltipText = 'Tooltip'; render(<RefreshLabel tooltipContent={tooltipText} onClick={jest.fn()} />); const refresh = screen.getByRole('button'); userEvent.hover(refresh); const tooltip = await screen.findByRole('tooltip'); expect(tooltip).toBeInTheDocument(); expect(tooltip).toHaveTextContent(tooltipText); }); test('triggers on click event', async () => { const onClick = jest.fn(); render(<RefreshLabel tooltipContent="Tooltip" onClick={onClick} />); const refresh = await screen.findByRole('button'); userEvent.click(refresh); expect(onClick).toHaveBeenCalled(); });
7,010
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/ResizableSidebar/useStoredSidebarWidth.test.ts
/** * 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 { renderHook, act } from '@testing-library/react-hooks'; import { LocalStorageKeys, setItem, getItem, } from 'src/utils/localStorageHelpers'; import useStoredSidebarWidth from './useStoredSidebarWidth'; const INITIAL_WIDTH = 300; describe('useStoredSidebarWidth', () => { beforeEach(() => { localStorage.clear(); }); afterAll(() => { localStorage.clear(); }); it('returns a default filterBar width by initialWidth', () => { const id = '123'; const { result } = renderHook(() => useStoredSidebarWidth(id, INITIAL_WIDTH), ); const [actualWidth] = result.current; expect(actualWidth).toEqual(INITIAL_WIDTH); }); it('returns a stored filterBar width from localStorage', () => { const id = '123'; const expectedWidth = 378; setItem(LocalStorageKeys.common__resizable_sidebar_widths, { [id]: expectedWidth, '456': 250, }); const { result } = renderHook(() => useStoredSidebarWidth(id, INITIAL_WIDTH), ); const [actualWidth] = result.current; expect(actualWidth).toEqual(expectedWidth); expect(actualWidth).not.toEqual(250); }); it('returns a setter for filterBar width that stores the state in localStorage together', () => { const id = '123'; const expectedWidth = 378; const otherDashboardId = '456'; const otherDashboardWidth = 253; setItem(LocalStorageKeys.common__resizable_sidebar_widths, { [id]: 300, [otherDashboardId]: otherDashboardWidth, }); const { result } = renderHook(() => useStoredSidebarWidth(id, INITIAL_WIDTH), ); const [prevWidth, setter] = result.current; expect(prevWidth).toEqual(300); act(() => setter(expectedWidth)); const updatedWidth = result.current[0]; const widthsMap = getItem( LocalStorageKeys.common__resizable_sidebar_widths, {}, ); expect(widthsMap[id]).toEqual(expectedWidth); expect(widthsMap[otherDashboardId]).toEqual(otherDashboardWidth); expect(updatedWidth).toEqual(expectedWidth); expect(updatedWidth).not.toEqual(250); }); });
7,013
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Select/AsyncSelect.test.tsx
/** * 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 { createEvent, fireEvent, render, screen, waitFor, within, } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import { AsyncSelect } from 'src/components'; const ARIA_LABEL = 'Test'; const NEW_OPTION = 'Kyle'; const NO_DATA = 'No Data'; const LOADING = 'Loading...'; const OPTIONS = [ { label: 'John', value: 1, gender: 'Male' }, { label: 'Liam', value: 2, gender: 'Male' }, { label: 'Olivia', value: 3, gender: 'Female' }, { label: 'Emma', value: 4, gender: 'Female' }, { label: 'Noah', value: 5, gender: 'Male' }, { label: 'Ava', value: 6, gender: 'Female' }, { label: 'Oliver', value: 7, gender: 'Male' }, { label: 'ElijahH', value: 8, gender: 'Male' }, { label: 'Charlotte', value: 9, gender: 'Female' }, { label: 'Giovanni', value: 10, gender: 'Male' }, { label: 'Franco', value: 11, gender: 'Male' }, { label: 'Sandro', value: 12, gender: 'Male' }, { label: 'Alehandro', value: 13, gender: 'Male' }, { label: 'Johnny', value: 14, gender: 'Male' }, { label: 'Nikole', value: 15, gender: 'Female' }, { label: 'Igor', value: 16, gender: 'Male' }, { label: 'Guilherme', value: 17, gender: 'Male' }, { label: 'Irfan', value: 18, gender: 'Male' }, { label: 'George', value: 19, gender: 'Male' }, { label: 'Ashfaq', value: 20, gender: 'Male' }, { label: 'Herme', value: 21, gender: 'Male' }, { label: 'Cher', value: 22, gender: 'Female' }, { label: 'Her', value: 23, gender: 'Male' }, ].sort((option1, option2) => option1.label.localeCompare(option2.label)); const NULL_OPTION = { label: '<NULL>', value: null } as unknown as { label: string; value: number; }; const loadOptions = async (search: string, page: number, pageSize: number) => { const totalCount = OPTIONS.length; const start = page * pageSize; const deleteCount = start + pageSize < totalCount ? pageSize : totalCount - start; const searchValue = search.trim().toLowerCase(); const optionFilterProps = ['label', 'value', 'gender']; const data = OPTIONS.filter(option => optionFilterProps.some(prop => { const optionProp = option?.[prop] ? String(option[prop]).trim().toLowerCase() : ''; return optionProp.includes(searchValue); }), ).splice(start, deleteCount); return { data, totalCount: OPTIONS.length, }; }; const defaultProps = { allowClear: true, ariaLabel: ARIA_LABEL, labelInValue: true, options: loadOptions, pageSize: 10, showSearch: true, }; const getElementByClassName = (className: string) => document.querySelector(className)! as HTMLElement; const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const getSelect = () => screen.getByRole('combobox', { name: ARIA_LABEL }); const getAllSelectOptions = () => getElementsByClassName('.ant-select-item-option-content'); const findSelectOption = (text: string) => waitFor(() => within(getElementByClassName('.rc-virtual-list')).getByText(text), ); const querySelectOption = (text: string) => waitFor(() => within(getElementByClassName('.rc-virtual-list')).queryByText(text), ); const findAllSelectOptions = () => waitFor(() => getElementsByClassName('.ant-select-item-option-content')); const findSelectValue = () => waitFor(() => getElementByClassName('.ant-select-selection-item')); const findAllSelectValues = () => waitFor(() => getElementsByClassName('.ant-select-selection-item')); const clearAll = () => userEvent.click(screen.getByLabelText('close-circle')); const matchOrder = async (expectedLabels: string[]) => { const actualLabels: string[] = []; (await findAllSelectOptions()).forEach(option => { actualLabels.push(option.textContent || ''); }); // menu is a virtual list, which means it may not render all options expect(actualLabels.slice(0, expectedLabels.length)).toEqual( expectedLabels.slice(0, actualLabels.length), ); return true; }; const type = (text: string) => { const select = getSelect(); userEvent.clear(select); return userEvent.type(select, text, { delay: 10 }); }; const open = () => waitFor(() => userEvent.click(getSelect())); test('displays a header', async () => { const headerText = 'Header'; render(<AsyncSelect {...defaultProps} header={headerText} />); expect(screen.getByText(headerText)).toBeInTheDocument(); }); test('adds a new option if the value is not in the options, when options are empty', async () => { const loadOptions = jest.fn(async () => ({ data: [], totalCount: 0 })); render( <AsyncSelect {...defaultProps} options={loadOptions} value={OPTIONS[0]} />, ); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); options.forEach((option, i) => expect(option).toHaveTextContent(OPTIONS[i].label), ); }); test('adds a new option if the value is not in the options, when options have values', async () => { const loadOptions = jest.fn(async () => ({ data: [OPTIONS[1]], totalCount: 1, })); render( <AsyncSelect {...defaultProps} options={loadOptions} value={OPTIONS[0]} />, ); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); expect(await findSelectOption(OPTIONS[1].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(2); options.forEach((option, i) => expect(option).toHaveTextContent(OPTIONS[i].label), ); }); test('does not add a new option if the value is already in the options', async () => { const loadOptions = jest.fn(async () => ({ data: [OPTIONS[0]], totalCount: 1, })); render( <AsyncSelect {...defaultProps} options={loadOptions} value={OPTIONS[0]} />, ); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); }); test('inverts the selection', async () => { render(<AsyncSelect {...defaultProps} invertSelection />); await open(); userEvent.click(await findSelectOption(OPTIONS[0].label)); expect(await screen.findByLabelText('stop')).toBeInTheDocument(); }); test('sort the options by label if no sort comparator is provided', async () => { const loadUnsortedOptions = jest.fn(async () => ({ data: [...OPTIONS].sort(() => Math.random()), totalCount: 2, })); render(<AsyncSelect {...defaultProps} options={loadUnsortedOptions} />); await open(); const options = await findAllSelectOptions(); options.forEach((option, key) => expect(option).toHaveTextContent(OPTIONS[key].label), ); }); test('sort the options using a custom sort comparator', async () => { const sortComparator = ( option1: typeof OPTIONS[0], option2: typeof OPTIONS[0], ) => option1.gender.localeCompare(option2.gender); render(<AsyncSelect {...defaultProps} sortComparator={sortComparator} />); await open(); const options = await findAllSelectOptions(); const optionsPage = OPTIONS.slice(0, defaultProps.pageSize); const sortedOptions = optionsPage.sort(sortComparator); options.forEach((option, key) => { expect(option).toHaveTextContent(sortedOptions[key].label); }); }); test('should sort selected to top when in single mode', async () => { render(<AsyncSelect {...defaultProps} mode="single" />); const originalLabels = OPTIONS.map(option => option.label); await open(); userEvent.click(await findSelectOption(originalLabels[1])); // after selection, keep the original order expect(await matchOrder(originalLabels)).toBe(true); // order selected to top when reopen await type('{esc}'); await open(); let labels = originalLabels.slice(); labels = labels.splice(1, 1).concat(labels); expect(await matchOrder(labels)).toBe(true); // keep clicking other items, the updated order should still based on // original order userEvent.click(await findSelectOption(originalLabels[5])); await matchOrder(labels); await type('{esc}'); await open(); labels = originalLabels.slice(); labels = labels.splice(5, 1).concat(labels); expect(await matchOrder(labels)).toBe(true); // should revert to original order clearAll(); await type('{esc}'); await open(); expect(await matchOrder(originalLabels)).toBe(true); }); test('should sort selected to the top when in multi mode', async () => { render(<AsyncSelect {...defaultProps} mode="multiple" />); const originalLabels = OPTIONS.map(option => option.label); let labels = originalLabels.slice(); await open(); userEvent.click(await findSelectOption(labels[1])); expect(await matchOrder(labels)).toBe(true); await type('{esc}'); await open(); labels = labels.splice(1, 1).concat(labels); expect(await matchOrder(labels)).toBe(true); await open(); userEvent.click(await findSelectOption(labels[5])); await type('{esc}'); await open(); labels = [labels.splice(0, 1)[0], labels.splice(4, 1)[0]].concat(labels); expect(await matchOrder(labels)).toBe(true); // should revert to original order clearAll(); await type('{esc}'); await open(); expect(await matchOrder(originalLabels)).toBe(true); }); test('searches for label or value', async () => { const option = OPTIONS[11]; render(<AsyncSelect {...defaultProps} />); const search = option.value; await type(search.toString()); expect(await findSelectOption(option.label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent(option.label); }); test('search order exact and startWith match first', async () => { render(<AsyncSelect {...defaultProps} />); await open(); await type('Her'); expect(await findSelectOption('Guilherme')).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options.length).toBe(4); expect(options[0]).toHaveTextContent('Her'); expect(options[1]).toHaveTextContent('Herme'); expect(options[2]).toHaveTextContent('Cher'); expect(options[3]).toHaveTextContent('Guilherme'); }); test('ignores case when searching', async () => { render(<AsyncSelect {...defaultProps} />); await type('george'); expect(await findSelectOption('George')).toBeInTheDocument(); }); test('same case should be ranked to the top', async () => { const loadOptions = jest.fn(async () => ({ data: [ { value: 'Cac' }, { value: 'abac' }, { value: 'acbc' }, { value: 'CAc' }, ], totalCount: 4, })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); await type('Ac'); await waitFor(() => { const options = getAllSelectOptions(); expect(options.length).toBe(4); expect(options[0]?.textContent).toEqual('acbc'); expect(options[1]?.textContent).toEqual('CAc'); expect(options[2]?.textContent).toEqual('abac'); expect(options[3]?.textContent).toEqual('Cac'); }); }); test('ignores special keys when searching', async () => { render(<AsyncSelect {...defaultProps} />); await type('{shift}'); expect(screen.queryByText(LOADING)).not.toBeInTheDocument(); }); test('searches for custom fields', async () => { render( <AsyncSelect {...defaultProps} optionFilterProps={['label', 'gender']} />, ); await open(); await type('Liam'); // Liam is on the second page. need to wait to fetch options expect(await findSelectOption('Liam')).toBeInTheDocument(); let options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent('Liam'); await type('Female'); // Olivia is on the second page. need to wait to fetch options expect(await findSelectOption('Olivia')).toBeInTheDocument(); options = await findAllSelectOptions(); expect(options.length).toBe(6); expect(options[0]).toHaveTextContent('Ava'); expect(options[1]).toHaveTextContent('Charlotte'); expect(options[2]).toHaveTextContent('Cher'); expect(options[3]).toHaveTextContent('Emma'); expect(options[4]).toHaveTextContent('Nikole'); expect(options[5]).toHaveTextContent('Olivia'); await type('1'); expect(await screen.findByText(NO_DATA)).toBeInTheDocument(); }); test('removes duplicated values', async () => { render(<AsyncSelect {...defaultProps} mode="multiple" allowNewOptions />); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => 'a,b,b,b,c,d,d', }, }); fireEvent(input, paste); const values = await findAllSelectValues(); expect(values.length).toBe(4); expect(values[0]).toHaveTextContent('a'); expect(values[1]).toHaveTextContent('b'); expect(values[2]).toHaveTextContent('c'); expect(values[3]).toHaveTextContent('d'); }); test('renders a custom label', async () => { const loadOptions = jest.fn(async () => ({ data: [ { label: 'John', value: 1, customLabel: <h1>John</h1> }, { label: 'Liam', value: 2, customLabel: <h1>Liam</h1> }, { label: 'Olivia', value: 3, customLabel: <h1>Olivia</h1> }, ], totalCount: 3, })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); await open(); expect(screen.getByRole('heading', { name: 'John' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Liam' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Olivia' })).toBeInTheDocument(); }); test('searches for a word with a custom label', async () => { const loadOptions = jest.fn(async () => ({ data: [ { label: 'John', value: 1, customLabel: <h1>John</h1> }, { label: 'Liam', value: 2, customLabel: <h1>Liam</h1> }, { label: 'Olivia', value: 3, customLabel: <h1>Olivia</h1> }, ], totalCount: 3, })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); await type('Liam'); const selectOptions = await findAllSelectOptions(); expect(selectOptions.length).toBe(1); expect(selectOptions[0]).toHaveTextContent('Liam'); }); test('removes a new option if the user does not select it', async () => { render(<AsyncSelect {...defaultProps} allowNewOptions />); await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); await type('k'); await waitFor(() => expect(screen.queryByText(NEW_OPTION)).not.toBeInTheDocument(), ); }); test('clear all the values', async () => { const onClear = jest.fn(); render( <AsyncSelect {...defaultProps} mode="multiple" value={[OPTIONS[0], OPTIONS[1]]} onClear={onClear} />, ); clearAll(); expect(onClear).toHaveBeenCalled(); const values = await findAllSelectValues(); expect(values.length).toBe(0); }); test('does not add a new option if allowNewOptions is false', async () => { render(<AsyncSelect {...defaultProps} />); await open(); await type(NEW_OPTION); expect(await screen.findByText(NO_DATA)).toBeInTheDocument(); }); test('adds the null option when selected in single mode', async () => { const loadOptions = jest.fn(async () => ({ data: [OPTIONS[0], NULL_OPTION], totalCount: 2, })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); await open(); userEvent.click(await findSelectOption(NULL_OPTION.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(NULL_OPTION.label); }); test('adds the null option when selected in multiple mode', async () => { const loadOptions = jest.fn(async () => ({ data: [OPTIONS[0], NULL_OPTION], totalCount: 2, })); render( <AsyncSelect {...defaultProps} options={loadOptions} mode="multiple" />, ); await open(); userEvent.click(await findSelectOption(OPTIONS[0].label)); userEvent.click(await findSelectOption(NULL_OPTION.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(OPTIONS[0].label); expect(values[1]).toHaveTextContent(NULL_OPTION.label); }); test('renders the select with default props', () => { render(<AsyncSelect {...defaultProps} />); expect(getSelect()).toBeInTheDocument(); }); test('opens the select without any data', async () => { render( <AsyncSelect {...defaultProps} options={async () => ({ data: [], totalCount: 0 })} />, ); await open(); expect(await screen.findByText(/no data/i)).toBeInTheDocument(); }); test('displays the loading indicator when opening', async () => { render(<AsyncSelect {...defaultProps} />); await waitFor(() => { userEvent.click(getSelect()); expect(screen.getByText(LOADING)).toBeInTheDocument(); }); expect(screen.queryByText(LOADING)).not.toBeInTheDocument(); }); test('makes a selection in single mode', async () => { render(<AsyncSelect {...defaultProps} />); const optionText = 'Emma'; await open(); userEvent.click(await findSelectOption(optionText)); expect(await findSelectValue()).toHaveTextContent(optionText); }); test('multiple selections in multiple mode', async () => { render(<AsyncSelect {...defaultProps} mode="multiple" />); await open(); const [firstOption, secondOption] = OPTIONS; userEvent.click(await findSelectOption(firstOption.label)); userEvent.click(await findSelectOption(secondOption.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(firstOption.label); expect(values[1]).toHaveTextContent(secondOption.label); }); test('changes the selected item in single mode', async () => { const onChange = jest.fn(); render(<AsyncSelect {...defaultProps} onChange={onChange} />); await open(); const [firstOption, secondOption] = OPTIONS; userEvent.click(await findSelectOption(firstOption.label)); expect(onChange).toHaveBeenCalledWith( expect.objectContaining({ label: firstOption.label, value: firstOption.value, }), expect.objectContaining(firstOption), ); expect(await findSelectValue()).toHaveTextContent(firstOption.label); userEvent.click(await findSelectOption(secondOption.label)); expect(onChange).toHaveBeenCalledWith( expect.objectContaining({ label: secondOption.label, value: secondOption.value, }), expect.objectContaining(secondOption), ); expect(await findSelectValue()).toHaveTextContent(secondOption.label); }); test('deselects an item in multiple mode', async () => { render(<AsyncSelect {...defaultProps} mode="multiple" />); await open(); const option3 = OPTIONS[2]; const option8 = OPTIONS[7]; userEvent.click(await findSelectOption(option8.label)); userEvent.click(await findSelectOption(option3.label)); let options = await findAllSelectOptions(); expect(options).toHaveLength(Math.min(defaultProps.pageSize, OPTIONS.length)); expect(options[0]).toHaveTextContent(OPTIONS[0].label); expect(options[1]).toHaveTextContent(OPTIONS[1].label); await type('{esc}'); await open(); // should rank selected options to the top after menu closes options = await findAllSelectOptions(); expect(options).toHaveLength(Math.min(defaultProps.pageSize, OPTIONS.length)); expect(options[0]).toHaveTextContent(option3.label); expect(options[1]).toHaveTextContent(option8.label); let values = await findAllSelectValues(); expect(values).toHaveLength(2); // should keep the order by which the options were selected expect(values[0]).toHaveTextContent(option8.label); expect(values[1]).toHaveTextContent(option3.label); userEvent.click(await findSelectOption(option3.label)); values = await findAllSelectValues(); expect(values.length).toBe(1); expect(values[0]).toHaveTextContent(option8.label); }); test('adds a new option if none is available and allowNewOptions is true', async () => { render(<AsyncSelect {...defaultProps} allowNewOptions />); await open(); await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); }); test('does not add a new option if the option already exists', async () => { render(<AsyncSelect {...defaultProps} allowNewOptions />); const option = OPTIONS[0].label; await open(); await type(option); await waitFor(() => { const array = within( getElementByClassName('.rc-virtual-list'), ).getAllByText(option); expect(array.length).toBe(1); }); }); test('shows "No data" when allowNewOptions is false and a new option is entered', async () => { render(<AsyncSelect {...defaultProps} allowNewOptions={false} showSearch />); await open(); await type(NEW_OPTION); expect(await screen.findByText(NO_DATA)).toBeInTheDocument(); }); test('does not show "No data" when allowNewOptions is true and a new option is entered', async () => { render(<AsyncSelect {...defaultProps} allowNewOptions />); await open(); await type(NEW_OPTION); await waitFor(() => expect(screen.queryByText(NO_DATA)).not.toBeInTheDocument(), ); }); test('sets a initial value in single mode', async () => { render(<AsyncSelect {...defaultProps} value={OPTIONS[0]} />); expect(await findSelectValue()).toHaveTextContent(OPTIONS[0].label); }); test('sets a initial value in multiple mode', async () => { render( <AsyncSelect {...defaultProps} mode="multiple" value={[OPTIONS[0], OPTIONS[1]]} />, ); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(OPTIONS[0].label); expect(values[1]).toHaveTextContent(OPTIONS[1].label); }); test('searches for matches in both loaded and unloaded pages', async () => { render(<AsyncSelect {...defaultProps} />); await open(); await type('and'); let options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent('Alehandro'); await screen.findByText('Sandro'); options = await findAllSelectOptions(); expect(options.length).toBe(2); expect(options[0]).toHaveTextContent('Alehandro'); expect(options[1]).toHaveTextContent('Sandro'); }); test('searches for an item in a page not loaded', async () => { const mock = jest.fn(loadOptions); render(<AsyncSelect {...defaultProps} options={mock} />); const search = 'Sandro'; await open(); await type(search); await waitFor(() => expect(mock).toHaveBeenCalledTimes(2)); const options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent(search); }); test('does not fetches data when rendering', async () => { const loadOptions = jest.fn(async () => ({ data: [], totalCount: 0 })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); expect(loadOptions).not.toHaveBeenCalled(); }); test('fetches data when opening', async () => { const loadOptions = jest.fn(async () => ({ data: [], totalCount: 0 })); render(<AsyncSelect {...defaultProps} options={loadOptions} />); await open(); expect(loadOptions).toHaveBeenCalled(); }); test('fetches data only after a search input is entered if fetchOnlyOnSearch is true', async () => { const loadOptions = jest.fn(async () => ({ data: [], totalCount: 0 })); render( <AsyncSelect {...defaultProps} options={loadOptions} fetchOnlyOnSearch />, ); await open(); await waitFor(() => expect(loadOptions).not.toHaveBeenCalled()); await type('search'); await waitFor(() => expect(loadOptions).toHaveBeenCalled()); }); test('displays an error message when an exception is thrown while fetching', async () => { const error = 'Fetch error'; const loadOptions = async () => { throw new Error(error); }; render(<AsyncSelect {...defaultProps} options={loadOptions} />); await open(); expect(screen.getByText(error)).toBeInTheDocument(); }); test('does not fire a new request for the same search input', async () => { const loadOptions = jest.fn(async () => ({ data: [], totalCount: 0 })); render( <AsyncSelect {...defaultProps} options={loadOptions} fetchOnlyOnSearch />, ); await type('search'); await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(1)); await type('search'); await waitFor(() => expect(loadOptions).toHaveBeenCalledTimes(1)); }); test('does not fire a new request if all values have been fetched', async () => { const mock = jest.fn(loadOptions); const search = 'George'; const pageSize = OPTIONS.length; render(<AsyncSelect {...defaultProps} options={mock} pageSize={pageSize} />); await open(); expect(mock).toHaveBeenCalledTimes(1); await type(search); expect(await findSelectOption(search)).toBeInTheDocument(); expect(mock).toHaveBeenCalledTimes(1); }); test('fires a new request if all values have not been fetched', async () => { const mock = jest.fn(loadOptions); const pageSize = OPTIONS.length / 2; render(<AsyncSelect {...defaultProps} options={mock} pageSize={pageSize} />); await open(); expect(mock).toHaveBeenCalledTimes(1); await type('or'); // `George` is on the first page so when it appears the API has not been called again expect(await findSelectOption('George')).toBeInTheDocument(); expect(mock).toHaveBeenCalledTimes(1); // `Igor` is on the second paged API request expect(await findSelectOption('Igor')).toBeInTheDocument(); expect(mock).toHaveBeenCalledTimes(2); }); test('does not render a helper text by default', async () => { render(<AsyncSelect {...defaultProps} />); await open(); expect(screen.queryByRole('note')).not.toBeInTheDocument(); }); test('renders a helper text when one is provided', async () => { const helperText = 'Helper text'; render(<AsyncSelect {...defaultProps} helperText={helperText} />); await open(); expect(screen.getByRole('note')).toBeInTheDocument(); expect(screen.queryByText(helperText)).toBeInTheDocument(); }); test('finds an element with a numeric value and does not duplicate the options', async () => { const options = jest.fn(async () => ({ data: [ { label: 'a', value: 11 }, { label: 'b', value: 12 }, ], totalCount: 2, })); render(<AsyncSelect {...defaultProps} options={options} allowNewOptions />); await open(); await type('11'); expect(await findSelectOption('a')).toBeInTheDocument(); expect(await querySelectOption('11')).not.toBeInTheDocument(); }); test('Renders only 1 tag and an overflow tag in oneLine mode', () => { render( <AsyncSelect {...defaultProps} value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]} mode="multiple" oneLine />, ); expect(screen.getByText(OPTIONS[0].label)).toBeVisible(); expect(screen.queryByText(OPTIONS[1].label)).not.toBeInTheDocument(); expect(screen.queryByText(OPTIONS[2].label)).not.toBeInTheDocument(); expect(screen.getByText('+ 2 ...')).toBeVisible(); }); test('Renders only an overflow tag if dropdown is open in oneLine mode', async () => { render( <AsyncSelect {...defaultProps} value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]} mode="multiple" oneLine />, ); await open(); const withinSelector = within(getElementByClassName('.ant-select-selector')); await waitFor(() => { expect( withinSelector.queryByText(OPTIONS[0].label), ).not.toBeInTheDocument(); expect( withinSelector.queryByText(OPTIONS[1].label), ).not.toBeInTheDocument(); expect( withinSelector.queryByText(OPTIONS[2].label), ).not.toBeInTheDocument(); expect(withinSelector.getByText('+ 3 ...')).toBeVisible(); }); await type('{esc}'); expect(await withinSelector.findByText(OPTIONS[0].label)).toBeVisible(); expect(withinSelector.queryByText(OPTIONS[1].label)).not.toBeInTheDocument(); expect(withinSelector.queryByText(OPTIONS[2].label)).not.toBeInTheDocument(); expect(withinSelector.getByText('+ 2 ...')).toBeVisible(); }); test('does not fire onChange when searching but no selection', async () => { const onChange = jest.fn(); render( <div role="main"> <AsyncSelect {...defaultProps} onChange={onChange} mode="multiple" allowNewOptions /> </div>, ); await open(); await type('Joh'); userEvent.click(await findSelectOption('John')); userEvent.click(screen.getByRole('main')); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when clearing the selection in single mode', async () => { const onChange = jest.fn(); render( <AsyncSelect {...defaultProps} onChange={onChange} mode="single" value={OPTIONS[0]} />, ); clearAll(); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when clearing the selection in multiple mode', async () => { const onChange = jest.fn(); render( <AsyncSelect {...defaultProps} onChange={onChange} mode="multiple" value={OPTIONS[0]} />, ); clearAll(); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when pasting a selection', async () => { const onChange = jest.fn(); render(<AsyncSelect {...defaultProps} onChange={onChange} />); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => OPTIONS[0].label, }, }); fireEvent(input, paste); expect(onChange).toHaveBeenCalledTimes(1); }); test('does not duplicate options when using numeric values', async () => { render( <AsyncSelect {...defaultProps} mode="multiple" options={async () => ({ data: [ { label: '1', value: 1 }, { label: '2', value: 2 }, ], totalCount: 2, })} />, ); await type('1'); await waitFor(() => expect(getAllSelectOptions().length).toBe(1)); }); test('pasting an existing option does not duplicate it', async () => { const options = jest.fn(async () => ({ data: [OPTIONS[0]], totalCount: 1, })); render(<AsyncSelect {...defaultProps} options={options} />); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => OPTIONS[0].label, }, }); fireEvent(input, paste); expect(await findAllSelectOptions()).toHaveLength(1); }); test('pasting an existing option does not duplicate it in multiple mode', async () => { const options = jest.fn(async () => ({ data: [ { label: 'John', value: 1 }, { label: 'Liam', value: 2 }, { label: 'Olivia', value: 3 }, ], totalCount: 3, })); render(<AsyncSelect {...defaultProps} options={options} mode="multiple" />); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => 'John,Liam,Peter', }, }); fireEvent(input, paste); // Only Peter should be added expect(await findAllSelectOptions()).toHaveLength(4); }); /* TODO: Add tests that require scroll interaction. Needs further investigation. - Fetches more data when scrolling and more data is available - Doesn't fetch more data when no more data is available - Requests the correct page and page size - Sets the page to zero when a new search is made */
7,017
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Select/Select.test.tsx
/** * 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 { createEvent, fireEvent, render, screen, waitFor, within, } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import Select from 'src/components/Select/Select'; import { SELECT_ALL_VALUE } from './utils'; type Option = { label: string; value: number; gender: string; disabled?: boolean; }; const ARIA_LABEL = 'Test'; const NEW_OPTION = 'Kyle'; const NO_DATA = 'No Data'; const LOADING = 'Loading...'; const OPTIONS: Option[] = [ { label: 'John', value: 1, gender: 'Male' }, { label: 'Liam', value: 2, gender: 'Male' }, { label: 'Olivia', value: 3, gender: 'Female' }, { label: 'Emma', value: 4, gender: 'Female' }, { label: 'Noah', value: 5, gender: 'Male' }, { label: 'Ava', value: 6, gender: 'Female' }, { label: 'Oliver', value: 7, gender: 'Male' }, { label: 'ElijahH', value: 8, gender: 'Male' }, { label: 'Charlotte', value: 9, gender: 'Female' }, { label: 'Giovanni', value: 10, gender: 'Male' }, { label: 'Franco', value: 11, gender: 'Male' }, { label: 'Sandro', value: 12, gender: 'Male' }, { label: 'Alehandro', value: 13, gender: 'Male' }, { label: 'Johnny', value: 14, gender: 'Male' }, { label: 'Nikole', value: 15, gender: 'Female' }, { label: 'Igor', value: 16, gender: 'Male' }, { label: 'Guilherme', value: 17, gender: 'Male' }, { label: 'Irfan', value: 18, gender: 'Male' }, { label: 'George', value: 19, gender: 'Male' }, { label: 'Ashfaq', value: 20, gender: 'Male' }, { label: 'Herme', value: 21, gender: 'Male' }, { label: 'Cher', value: 22, gender: 'Female' }, { label: 'Her', value: 23, gender: 'Male' }, ].sort((option1, option2) => option1.label.localeCompare(option2.label)); const NULL_OPTION = { label: '<NULL>', value: null } as unknown as { label: string; value: number; }; const defaultProps = { allowClear: true, ariaLabel: ARIA_LABEL, labelInValue: true, options: OPTIONS, showSearch: true, }; const selectAllOptionLabel = (numOptions: number) => `${String(SELECT_ALL_VALUE)} (${numOptions})`; const getElementByClassName = (className: string) => document.querySelector(className)! as HTMLElement; const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const getSelect = () => screen.getByRole('combobox', { name: ARIA_LABEL }); const findSelectOption = (text: string) => waitFor(() => within(getElementByClassName('.rc-virtual-list')).getByText(text), ); const querySelectOption = (text: string) => waitFor(() => within(getElementByClassName('.rc-virtual-list')).queryByText(text), ); const getAllSelectOptions = () => getElementsByClassName('.ant-select-item-option-content'); const findAllSelectOptions = () => waitFor(() => getElementsByClassName('.ant-select-item-option-content')); const findSelectValue = () => waitFor(() => getElementByClassName('.ant-select-selection-item')); const findAllSelectValues = () => waitFor(() => [...getElementsByClassName('.ant-select-selection-item')]); const findAllCheckedValues = () => waitFor(() => [ ...getElementsByClassName('.ant-select-item-option-selected'), ]); const clearAll = () => userEvent.click(screen.getByLabelText('close-circle')); const matchOrder = async (expectedLabels: string[]) => { const actualLabels: string[] = []; (await findAllSelectOptions()).forEach(option => { actualLabels.push(option.textContent || ''); }); // menu is a virtual list, which means it may not render all options expect(actualLabels.slice(0, expectedLabels.length)).toEqual( expectedLabels.slice(0, actualLabels.length), ); return true; }; const type = (text: string) => { const select = getSelect(); userEvent.clear(select); return userEvent.type(select, text, { delay: 10 }); }; const clearTypedText = () => { const select = getSelect(); userEvent.clear(select); }; const open = () => waitFor(() => userEvent.click(getSelect())); const reopen = async () => { await type('{esc}'); await open(); }; test('displays a header', async () => { const headerText = 'Header'; render(<Select {...defaultProps} header={headerText} />); expect(screen.getByText(headerText)).toBeInTheDocument(); }); test('adds a new option if the value is not in the options, when options are empty', async () => { render(<Select {...defaultProps} options={[]} value={OPTIONS[0]} />); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); options.forEach((option, i) => expect(option).toHaveTextContent(OPTIONS[i].label), ); }); test('adds a new option if the value is not in the options, when options have values', async () => { render( <Select {...defaultProps} options={[OPTIONS[1]]} value={OPTIONS[0]} />, ); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); expect(await findSelectOption(OPTIONS[1].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(2); options.forEach((option, i) => expect(option).toHaveTextContent(OPTIONS[i].label), ); }); test('does not add a new option if the value is already in the options', async () => { render( <Select {...defaultProps} options={[OPTIONS[0]]} value={OPTIONS[0]} />, ); await open(); expect(await findSelectOption(OPTIONS[0].label)).toBeInTheDocument(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); }); test('inverts the selection', async () => { render(<Select {...defaultProps} invertSelection />); await open(); userEvent.click(await findSelectOption(OPTIONS[0].label)); expect(await screen.findByLabelText('stop')).toBeInTheDocument(); }); test('sort the options by label if no sort comparator is provided', async () => { const unsortedOptions = [...OPTIONS].sort(() => Math.random()); render(<Select {...defaultProps} options={unsortedOptions} />); await open(); const options = await findAllSelectOptions(); options.forEach((option, key) => expect(option).toHaveTextContent(OPTIONS[key].label), ); }); test('should sort selected to top when in single mode', async () => { render(<Select {...defaultProps} mode="single" />); const originalLabels = OPTIONS.map(option => option.label); await open(); userEvent.click(await findSelectOption(originalLabels[1])); // after selection, keep the original order expect(await matchOrder(originalLabels)).toBe(true); // order selected to top when reopen await reopen(); let labels = originalLabels.slice(); labels = labels.splice(1, 1).concat(labels); expect(await matchOrder(labels)).toBe(true); // keep clicking other items, the updated order should still based on // original order userEvent.click(await findSelectOption(originalLabels[5])); await matchOrder(labels); await reopen(); labels = originalLabels.slice(); labels = labels.splice(5, 1).concat(labels); expect(await matchOrder(labels)).toBe(true); // should revert to original order clearAll(); await reopen(); expect(await matchOrder(originalLabels)).toBe(true); }); test('should sort selected to the top when in multi mode', async () => { render(<Select {...defaultProps} mode="multiple" />); const originalLabels = OPTIONS.map(option => option.label); let labels = originalLabels.slice(); await open(); userEvent.click(await findSelectOption(labels[2])); expect( await matchOrder([selectAllOptionLabel(originalLabels.length), ...labels]), ).toBe(true); await reopen(); labels = labels.splice(2, 1).concat(labels); expect( await matchOrder([selectAllOptionLabel(originalLabels.length), ...labels]), ).toBe(true); await open(); userEvent.click(await findSelectOption(labels[5])); await reopen(); labels = [labels.splice(0, 1)[0], labels.splice(4, 1)[0]].concat(labels); expect( await matchOrder([selectAllOptionLabel(originalLabels.length), ...labels]), ).toBe(true); // should revert to original order clearAll(); await reopen(); expect( await matchOrder([ selectAllOptionLabel(originalLabels.length), ...originalLabels, ]), ).toBe(true); }); test('searches for label or value', async () => { const option = OPTIONS[11]; render(<Select {...defaultProps} />); const search = option.value; await type(search.toString()); const options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent(option.label); }); test('search order exact and startWith match first', async () => { render(<Select {...defaultProps} />); await type('Her'); await waitFor(() => { const options = getAllSelectOptions(); expect(options.length).toBe(4); expect(options[0]?.textContent).toEqual('Her'); expect(options[1]?.textContent).toEqual('Herme'); expect(options[2]?.textContent).toEqual('Cher'); expect(options[3]?.textContent).toEqual('Guilherme'); }); }); test('ignores case when searching', async () => { render(<Select {...defaultProps} />); await type('george'); expect(await findSelectOption('George')).toBeInTheDocument(); }); test('same case should be ranked to the top', async () => { render( <Select {...defaultProps} options={[ { value: 'Cac' }, { value: 'abac' }, { value: 'acbc' }, { value: 'CAc' }, ]} />, ); await type('Ac'); await waitFor(() => { const options = getAllSelectOptions(); expect(options.length).toBe(4); expect(options[0]?.textContent).toEqual('acbc'); expect(options[1]?.textContent).toEqual('CAc'); expect(options[2]?.textContent).toEqual('abac'); expect(options[3]?.textContent).toEqual('Cac'); }); }); test('ignores special keys when searching', async () => { render(<Select {...defaultProps} />); await type('{shift}'); expect(screen.queryByText(LOADING)).not.toBeInTheDocument(); }); test('searches for custom fields', async () => { render(<Select {...defaultProps} optionFilterProps={['label', 'gender']} />); await type('Liam'); let options = await findAllSelectOptions(); expect(options.length).toBe(1); expect(options[0]).toHaveTextContent('Liam'); await type('Female'); options = await findAllSelectOptions(); expect(options.length).toBe(6); expect(options[0]).toHaveTextContent('Ava'); expect(options[1]).toHaveTextContent('Charlotte'); expect(options[2]).toHaveTextContent('Cher'); expect(options[3]).toHaveTextContent('Emma'); expect(options[4]).toHaveTextContent('Nikole'); expect(options[5]).toHaveTextContent('Olivia'); await type('1'); expect(screen.getByText(NO_DATA)).toBeInTheDocument(); }); test('removes duplicated values', async () => { render(<Select {...defaultProps} mode="multiple" allowNewOptions />); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => 'a,b,b,b,c,d,d', }, }); fireEvent(input, paste); const values = await findAllSelectValues(); expect(values.length).toBe(4); expect(values[0]).toHaveTextContent('a'); expect(values[1]).toHaveTextContent('b'); expect(values[2]).toHaveTextContent('c'); expect(values[3]).toHaveTextContent('d'); }); test('renders a custom label', async () => { const options = [ { label: 'John', value: 1, customLabel: <h1>John</h1> }, { label: 'Liam', value: 2, customLabel: <h1>Liam</h1> }, { label: 'Olivia', value: 3, customLabel: <h1>Olivia</h1> }, ]; render(<Select {...defaultProps} options={options} />); await open(); expect(screen.getByRole('heading', { name: 'John' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Liam' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Olivia' })).toBeInTheDocument(); }); test('searches for a word with a custom label', async () => { const options = [ { label: 'John', value: 1, customLabel: <h1>John</h1> }, { label: 'Liam', value: 2, customLabel: <h1>Liam</h1> }, { label: 'Olivia', value: 3, customLabel: <h1>Olivia</h1> }, ]; render(<Select {...defaultProps} options={options} />); await type('Liam'); const selectOptions = await findAllSelectOptions(); expect(selectOptions.length).toBe(1); expect(selectOptions[0]).toHaveTextContent('Liam'); }); test('removes a new option if the user does not select it', async () => { render(<Select {...defaultProps} allowNewOptions />); await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); await type('k'); await waitFor(() => expect(screen.queryByText(NEW_OPTION)).not.toBeInTheDocument(), ); }); test('clear all the values', async () => { const onClear = jest.fn(); render( <Select {...defaultProps} mode="multiple" value={[OPTIONS[0], OPTIONS[1]]} onClear={onClear} />, ); clearAll(); expect(onClear).toHaveBeenCalled(); const values = await findAllSelectValues(); expect(values.length).toBe(0); }); test('does not add a new option if allowNewOptions is false', async () => { render(<Select {...defaultProps} options={OPTIONS} />); await open(); await type(NEW_OPTION); expect(await screen.findByText(NO_DATA)).toBeInTheDocument(); }); test('adds the null option when selected in single mode', async () => { render(<Select {...defaultProps} options={[OPTIONS[0], NULL_OPTION]} />); await open(); userEvent.click(await findSelectOption(NULL_OPTION.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(NULL_OPTION.label); }); test('adds the null option when selected in multiple mode', async () => { render( <Select {...defaultProps} options={[OPTIONS[0], NULL_OPTION, OPTIONS[2]]} mode="multiple" />, ); await open(); userEvent.click(await findSelectOption(OPTIONS[0].label)); userEvent.click(await findSelectOption(NULL_OPTION.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(OPTIONS[0].label); expect(values[1]).toHaveTextContent(NULL_OPTION.label); }); test('renders the select with default props', () => { render(<Select {...defaultProps} />); expect(getSelect()).toBeInTheDocument(); }); test('opens the select without any data', async () => { render(<Select {...defaultProps} options={[]} />); await open(); expect(screen.getByText(NO_DATA)).toBeInTheDocument(); }); test('makes a selection in single mode', async () => { render(<Select {...defaultProps} />); const optionText = 'Emma'; await open(); userEvent.click(await findSelectOption(optionText)); expect(await findSelectValue()).toHaveTextContent(optionText); }); test('multiple selections in multiple mode', async () => { render(<Select {...defaultProps} mode="multiple" />); await open(); const [firstOption, secondOption] = OPTIONS; userEvent.click(await findSelectOption(firstOption.label)); userEvent.click(await findSelectOption(secondOption.label)); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(firstOption.label); expect(values[1]).toHaveTextContent(secondOption.label); }); test('changes the selected item in single mode', async () => { const onChange = jest.fn(); render(<Select {...defaultProps} onChange={onChange} />); await open(); const [firstOption, secondOption] = OPTIONS; userEvent.click(await findSelectOption(firstOption.label)); expect(await findSelectValue()).toHaveTextContent(firstOption.label); expect(onChange).toHaveBeenCalledWith( expect.objectContaining({ label: firstOption.label, value: firstOption.value, }), expect.objectContaining(firstOption), ); userEvent.click(await findSelectOption(secondOption.label)); expect(onChange).toHaveBeenCalledWith( expect.objectContaining({ label: secondOption.label, value: secondOption.value, }), expect.objectContaining(secondOption), ); expect(await findSelectValue()).toHaveTextContent(secondOption.label); }); test('deselects an item in multiple mode', async () => { render(<Select {...defaultProps} mode="multiple" />); await open(); const [firstOption, secondOption] = OPTIONS; userEvent.click(await findSelectOption(firstOption.label)); userEvent.click(await findSelectOption(secondOption.label)); let values = await findAllSelectValues(); expect(values.length).toBe(2); expect(values[0]).toHaveTextContent(firstOption.label); expect(values[1]).toHaveTextContent(secondOption.label); userEvent.click(await findSelectOption(firstOption.label)); values = await findAllSelectValues(); expect(values.length).toBe(1); expect(values[0]).toHaveTextContent(secondOption.label); }); test('adds a new option if none is available and allowNewOptions is true', async () => { render(<Select {...defaultProps} allowNewOptions />); await open(); await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); }); test('shows "No data" when allowNewOptions is false and a new option is entered', async () => { render(<Select {...defaultProps} allowNewOptions={false} />); await open(); await type(NEW_OPTION); expect(await screen.findByText(NO_DATA)).toBeInTheDocument(); }); test('does not show "No data" when allowNewOptions is true and a new option is entered', async () => { render(<Select {...defaultProps} allowNewOptions />); await open(); await type(NEW_OPTION); await waitFor(() => expect(screen.queryByText(NO_DATA)).not.toBeInTheDocument(), ); }); test('does not show "Loading..." when allowNewOptions is false and a new option is entered', async () => { render(<Select {...defaultProps} allowNewOptions={false} />); await open(); await type(NEW_OPTION); expect(screen.queryByText(LOADING)).not.toBeInTheDocument(); }); test('does not add a new option if the option already exists', async () => { render(<Select {...defaultProps} allowNewOptions />); const option = OPTIONS[0].label; await open(); await type(option); expect(await findSelectOption(option)).toBeInTheDocument(); }); test('sets a initial value in single mode', async () => { render(<Select {...defaultProps} value={OPTIONS[0]} />); expect(await findSelectValue()).toHaveTextContent(OPTIONS[0].label); }); test('sets a initial value in multiple mode', async () => { render( <Select {...defaultProps} mode="multiple" value={[OPTIONS[0], OPTIONS[1]]} />, ); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(OPTIONS[0].label); expect(values[1]).toHaveTextContent(OPTIONS[1].label); }); test('searches for an item', async () => { render(<Select {...defaultProps} />); const search = 'Oli'; await type(search); const options = await findAllSelectOptions(); expect(options.length).toBe(2); expect(options[0]).toHaveTextContent('Oliver'); expect(options[1]).toHaveTextContent('Olivia'); }); test('triggers getPopupContainer if passed', async () => { const getPopupContainer = jest.fn(); render(<Select {...defaultProps} getPopupContainer={getPopupContainer} />); await open(); expect(getPopupContainer).toHaveBeenCalled(); }); test('does not render a helper text by default', async () => { render(<Select {...defaultProps} />); await open(); expect(screen.queryByRole('note')).not.toBeInTheDocument(); }); test('renders a helper text when one is provided', async () => { const helperText = 'Helper text'; render(<Select {...defaultProps} helperText={helperText} />); await open(); expect(screen.getByRole('note')).toBeInTheDocument(); expect(screen.queryByText(helperText)).toBeInTheDocument(); }); test('finds an element with a numeric value and does not duplicate the options', async () => { const options = [ { label: 'a', value: 11 }, { label: 'b', value: 12 }, ]; render(<Select {...defaultProps} options={options} allowNewOptions />); await open(); await type('11'); expect(await findSelectOption('a')).toBeInTheDocument(); expect(await querySelectOption('11')).not.toBeInTheDocument(); }); test('render "Select all" for multi select', async () => { render(<Select {...defaultProps} mode="multiple" options={OPTIONS} />); await open(); const options = await findAllSelectOptions(); expect(options[0]).toHaveTextContent(selectAllOptionLabel(OPTIONS.length)); }); test('does not render "Select all" for single select', async () => { render(<Select {...defaultProps} options={OPTIONS} mode="single" />); await open(); expect( screen.queryByText(selectAllOptionLabel(OPTIONS.length)), ).not.toBeInTheDocument(); }); test('does not render "Select all" for an empty multiple select', async () => { render(<Select {...defaultProps} options={[]} mode="multiple" />); await open(); expect( screen.queryByText(selectAllOptionLabel(OPTIONS.length)), ).not.toBeInTheDocument(); }); test('does not render "Select all" when searching', async () => { render(<Select {...defaultProps} options={OPTIONS} mode="multiple" />); await open(); await type('Select'); await waitFor(() => expect( screen.queryByText(selectAllOptionLabel(OPTIONS.length)), ).not.toBeInTheDocument(), ); }); test('does not render "Select all" as one of the tags after selection', async () => { render(<Select {...defaultProps} options={OPTIONS} mode="multiple" />); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(OPTIONS.length))); const values = await findAllSelectValues(); expect(values[0]).not.toHaveTextContent(selectAllOptionLabel(OPTIONS.length)); }); test('keeps "Select all" at the top after a selection', async () => { const selected = OPTIONS[2]; render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" value={[selected]} />, ); await open(); const options = await findAllSelectOptions(); expect(options[0]).toHaveTextContent(selectAllOptionLabel(10)); expect(options[1]).toHaveTextContent(selected.label); }); test('selects all values', async () => { render( <Select {...defaultProps} options={OPTIONS} mode="multiple" maxTagCount={0} />, ); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(OPTIONS.length))); const values = await findAllSelectValues(); expect(values.length).toBe(1); expect(values[0]).toHaveTextContent(`+ ${OPTIONS.length} ...`); }); test('unselects all values', async () => { render( <Select {...defaultProps} options={OPTIONS} mode="multiple" maxTagCount={0} />, ); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(OPTIONS.length))); let values = await findAllSelectValues(); expect(values.length).toBe(1); expect(values[0]).toHaveTextContent(`+ ${OPTIONS.length} ...`); userEvent.click(await findSelectOption(selectAllOptionLabel(OPTIONS.length))); values = await findAllSelectValues(); expect(values.length).toBe(0); }); test('deselecting a value also deselects "Select all"', async () => { render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" maxTagCount={0} />, ); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(10))); let values = await findAllCheckedValues(); expect(values[0]).toHaveTextContent(selectAllOptionLabel(10)); userEvent.click(await findSelectOption(OPTIONS[0].label)); values = await findAllCheckedValues(); expect(values[0]).not.toHaveTextContent(selectAllOptionLabel(10)); }); test('deselecting a new value also removes it from the options', async () => { render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" allowNewOptions />, ); await open(); await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); await type('{enter}'); clearTypedText(); userEvent.click(await findSelectOption(NEW_OPTION)); expect(await querySelectOption(NEW_OPTION)).not.toBeInTheDocument(); }); test('selecting all values also selects "Select all"', async () => { render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" maxTagCount={0} />, ); await open(); const options = await findAllSelectOptions(); options.forEach((option, index) => { // skip select all if (index > 0) { userEvent.click(option); } }); const values = await findAllSelectValues(); expect(values[0]).toHaveTextContent(`+ 10 ...`); }); test('Renders only 1 tag and an overflow tag in oneLine mode', () => { render( <Select {...defaultProps} value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]} mode="multiple" oneLine />, ); expect(screen.getByText(OPTIONS[0].label)).toBeVisible(); expect(screen.queryByText(OPTIONS[1].label)).not.toBeInTheDocument(); expect(screen.queryByText(OPTIONS[2].label)).not.toBeInTheDocument(); expect(screen.getByText('+ 2 ...')).toBeVisible(); }); test('Renders only an overflow tag if dropdown is open in oneLine mode', async () => { render( <Select {...defaultProps} value={[OPTIONS[0], OPTIONS[1], OPTIONS[2]]} mode="multiple" oneLine />, ); await open(); const withinSelector = within(getElementByClassName('.ant-select-selector')); await waitFor(() => { expect( withinSelector.queryByText(OPTIONS[0].label), ).not.toBeInTheDocument(); expect( withinSelector.queryByText(OPTIONS[1].label), ).not.toBeInTheDocument(); expect( withinSelector.queryByText(OPTIONS[2].label), ).not.toBeInTheDocument(); expect(withinSelector.getByText('+ 3 ...')).toBeVisible(); }); await type('{esc}'); expect(await withinSelector.findByText(OPTIONS[0].label)).toBeVisible(); expect(withinSelector.queryByText(OPTIONS[1].label)).not.toBeInTheDocument(); expect(withinSelector.queryByText(OPTIONS[2].label)).not.toBeInTheDocument(); expect(withinSelector.getByText('+ 2 ...')).toBeVisible(); }); test('+N tag does not count the "Select All" option', async () => { render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" maxTagCount={0} />, ); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(10))); const values = await findAllSelectValues(); // maxTagCount is 0 so the +N tag should be + 10 ... expect(values[0]).toHaveTextContent('+ 10 ...'); }); test('"Select All" is checked when unchecking a newly added option and all the other options are still selected', async () => { render( <Select {...defaultProps} options={OPTIONS.slice(0, 10)} mode="multiple" allowNewOptions />, ); await open(); userEvent.click(await findSelectOption(selectAllOptionLabel(10))); expect(await findSelectOption(selectAllOptionLabel(10))).toBeInTheDocument(); // add a new option await type(NEW_OPTION); expect(await findSelectOption(NEW_OPTION)).toBeInTheDocument(); clearTypedText(); expect(await findSelectOption(selectAllOptionLabel(11))).toBeInTheDocument(); // select all should be selected let values = await findAllCheckedValues(); expect(values[0]).toHaveTextContent(selectAllOptionLabel(11)); // remove new option userEvent.click(await findSelectOption(NEW_OPTION)); // select all should still be selected values = await findAllCheckedValues(); expect(values[0]).toHaveTextContent(selectAllOptionLabel(10)); expect(await findSelectOption(selectAllOptionLabel(10))).toBeInTheDocument(); }); test('does not render "Select All" when there are 0 or 1 options', async () => { const { rerender } = render( <Select {...defaultProps} options={[]} mode="multiple" allowNewOptions />, ); await open(); expect(screen.queryByText(selectAllOptionLabel(0))).not.toBeInTheDocument(); rerender( <Select {...defaultProps} options={OPTIONS.slice(0, 1)} mode="multiple" allowNewOptions />, ); await open(); expect(screen.queryByText(selectAllOptionLabel(1))).not.toBeInTheDocument(); rerender( <Select {...defaultProps} options={OPTIONS.slice(0, 2)} mode="multiple" allowNewOptions />, ); await open(); expect(screen.getByText(selectAllOptionLabel(2))).toBeInTheDocument(); }); test('do not count unselected disabled options in "Select All"', async () => { const options = [...OPTIONS]; options[0].disabled = true; options[1].disabled = true; render( <Select {...defaultProps} options={options} mode="multiple" value={options[0]} />, ); await open(); // We have 2 options disabled but one is selected initially // Select All should count one and ignore the other expect( screen.getByText(selectAllOptionLabel(OPTIONS.length - 1)), ).toBeInTheDocument(); }); test('"Select All" does not affect disabled options', async () => { const options = [...OPTIONS]; options[0].disabled = true; options[1].disabled = true; render( <Select {...defaultProps} options={options} mode="multiple" value={options[0]} />, ); await open(); // We have 2 options disabled but one is selected initially expect(await findSelectValue()).toHaveTextContent(options[0].label); expect(await findSelectValue()).not.toHaveTextContent(options[1].label); // Checking Select All shouldn't affect the disabled options const selectAll = selectAllOptionLabel(OPTIONS.length - 1); userEvent.click(await findSelectOption(selectAll)); expect(await findSelectValue()).toHaveTextContent(options[0].label); expect(await findSelectValue()).not.toHaveTextContent(options[1].label); // Unchecking Select All shouldn't affect the disabled options userEvent.click(await findSelectOption(selectAll)); expect(await findSelectValue()).toHaveTextContent(options[0].label); expect(await findSelectValue()).not.toHaveTextContent(options[1].label); }); test('does not fire onChange when searching but no selection', async () => { const onChange = jest.fn(); render( <div role="main"> <Select {...defaultProps} onChange={onChange} mode="multiple" allowNewOptions /> </div>, ); await open(); await type('Joh'); userEvent.click(await findSelectOption('John')); userEvent.click(screen.getByRole('main')); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when clearing the selection in single mode', async () => { const onChange = jest.fn(); render( <Select {...defaultProps} onChange={onChange} mode="single" value={OPTIONS[0]} />, ); clearAll(); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when clearing the selection in multiple mode', async () => { const onChange = jest.fn(); render( <Select {...defaultProps} onChange={onChange} mode="multiple" value={OPTIONS[0]} />, ); clearAll(); expect(onChange).toHaveBeenCalledTimes(1); }); test('fires onChange when pasting a selection', async () => { const onChange = jest.fn(); render(<Select {...defaultProps} onChange={onChange} />); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => OPTIONS[0].label, }, }); fireEvent(input, paste); expect(onChange).toHaveBeenCalledTimes(1); }); test('does not duplicate options when using numeric values', async () => { render( <Select {...defaultProps} mode="multiple" options={[ { label: '1', value: 1 }, { label: '2', value: 2 }, ]} />, ); await type('1'); await waitFor(() => expect(getAllSelectOptions().length).toBe(1)); }); test('pasting an existing option does not duplicate it', async () => { render(<Select {...defaultProps} options={[OPTIONS[0]]} />); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => OPTIONS[0].label, }, }); fireEvent(input, paste); expect(await findAllSelectOptions()).toHaveLength(1); }); test('pasting an existing option does not duplicate it in multiple mode', async () => { const options = [ { label: 'John', value: 1 }, { label: 'Liam', value: 2 }, { label: 'Olivia', value: 3 }, ]; render( <Select {...defaultProps} options={options} mode="multiple" allowSelectAll={false} />, ); await open(); const input = getElementByClassName('.ant-select-selection-search-input'); const paste = createEvent.paste(input, { clipboardData: { getData: () => 'John,Liam,Peter', }, }); fireEvent(input, paste); // Only Peter should be added expect(await findAllSelectOptions()).toHaveLength(4); }); /* TODO: Add tests that require scroll interaction. Needs further investigation. - Fetches more data when scrolling and more data is available - Doesn't fetch more data when no more data is available - Requests the correct page and page size - Sets the page to zero when a new search is made */
7,029
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Table/Table.test.tsx
/** * 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 type { ColumnsType } from 'antd/es/table'; import { Table, TableSize } from './index'; interface BasicData { columnName: string; columnType: string; dataType: string; } const testData: BasicData[] = [ { columnName: 'Number', columnType: 'Numerical', dataType: 'number', }, { columnName: 'String', columnType: 'Physical', dataType: 'string', }, { columnName: 'Date', columnType: 'Virtual', dataType: 'date', }, ]; const testColumns: ColumnsType<BasicData> = [ { title: 'Column Name', dataIndex: 'columnName', key: 'columnName', }, { title: 'Column Type', dataIndex: 'columnType', key: 'columnType', }, { title: 'Data Type', dataIndex: 'dataType', key: 'dataType', }, ]; test('renders with default props', async () => { render( <Table size={TableSize.MIDDLE} columns={testColumns} data={testData} />, ); await waitFor(() => testColumns.forEach(column => expect(screen.getByText(column.title as string)).toBeInTheDocument(), ), ); testData.forEach(row => { expect(screen.getByText(row.columnName)).toBeInTheDocument(); expect(screen.getByText(row.columnType)).toBeInTheDocument(); expect(screen.getByText(row.dataType)).toBeInTheDocument(); }); });
7,032
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Table/sorters.test.ts
/** * 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 { alphabeticalSort, numericalSort } from './sorters'; const rows = [ { name: 'Deathstar Lamp', category: 'Lamp', cost: 75.99, }, { name: 'Desk Lamp', category: 'Lamp', cost: 15.99, }, { name: 'Bedside Lamp', category: 'Lamp', cost: 15.99, }, { name: 'Drafting Desk', category: 'Desk', cost: 125 }, { name: 'Sit / Stand Desk', category: 'Desk', cost: 275.99 }, ]; /** * NOTE: Sorters for antd table use < 0, 0, > 0 for sorting * -1 or less means the first item comes after the second item * 0 means the items sort values is equivalent * 1 or greater means the first item comes before the second item */ test('alphabeticalSort sorts correctly', () => { expect(alphabeticalSort('name', rows[0], rows[1])).toBe(-1); expect(alphabeticalSort('name', rows[1], rows[0])).toBe(1); expect(alphabeticalSort('category', rows[1], rows[0])).toBe(0); }); test('numericalSort sorts correctly', () => { expect(numericalSort('cost', rows[1], rows[2])).toBe(0); expect(numericalSort('cost', rows[1], rows[0])).toBeLessThan(0); expect(numericalSort('cost', rows[4], rows[1])).toBeGreaterThan(0); }); /** * We want to make sure our sorters do not throw runtime errors given bad inputs. * Runtime Errors in a sorter will cause a catastrophic React lifecycle error and produce white screen of death * In the case the sorter cannot perform the comparison it should return undefined and the next sort step will proceed without error */ test('alphabeticalSort bad inputs no errors', () => { // @ts-ignore expect(alphabeticalSort('name', null, null)).toBe(undefined); // incorrect non-object values // @ts-ignore expect(alphabeticalSort('name', 3, [])).toBe(undefined); // incorrect object values without specificed key expect(alphabeticalSort('name', {}, {})).toBe(undefined); // Object as value for name when it should be a string expect( alphabeticalSort( 'name', { name: { title: 'the name attribute should not be an object' } }, { name: 'Doug' }, ), ).toBe(undefined); }); test('numericalSort bad inputs no errors', () => { // @ts-ignore expect(numericalSort('name', undefined, undefined)).toBe(NaN); // @ts-ignore expect(numericalSort('name', null, null)).toBe(NaN); // incorrect non-object values // @ts-ignore expect(numericalSort('name', 3, [])).toBe(NaN); // incorrect object values without specified key expect(numericalSort('name', {}, {})).toBe(NaN); // Object as value for name when it should be a string expect( numericalSort( 'name', { name: { title: 'the name attribute should not be an object' } }, { name: 'Doug' }, ), ).toBe(NaN); });
7,037
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/ActionCell/ActionCell.test.tsx
/** * 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 ActionCell, { appendDataToMenu } from './index'; import { exampleMenuOptions, exampleRow } from './fixtures'; test('renders with default props', async () => { const clickHandler = jest.fn(); exampleMenuOptions[0].onClick = clickHandler; render(<ActionCell menuOptions={exampleMenuOptions} row={exampleRow} />); // Open the menu userEvent.click(await screen.findByTestId('dropdown-trigger')); // verify all of the menu items are being displayed exampleMenuOptions.forEach((item, index) => { expect(screen.getByText(item.label)).toBeInTheDocument(); if (index === 0) { // verify the menu items' onClick gets invoked userEvent.click(screen.getByText(item.label)); } }); expect(clickHandler).toHaveBeenCalled(); }); /** * Validate that the appendDataToMenu utility function used within the * Action cell menu rendering works as expected */ test('appendDataToMenu utility', () => { exampleMenuOptions.forEach(item => expect(item?.row).toBeUndefined()); const modifiedMenuOptions = appendDataToMenu(exampleMenuOptions, exampleRow); modifiedMenuOptions.forEach(item => expect(item?.row).toBeDefined()); });
7,041
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/BooleanCell/BooleanCell.test.tsx
/** * 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 { BOOL_FALSE_DISPLAY, BOOL_TRUE_DISPLAY } from 'src/constants'; import BooleanCell from '.'; test('renders true value', async () => { render(<BooleanCell value />); expect(screen.getByText(BOOL_TRUE_DISPLAY)).toBeInTheDocument(); }); test('renders false value', async () => { render(<BooleanCell value={false} />); expect(screen.getByText(BOOL_FALSE_DISPLAY)).toBeInTheDocument(); }); test('renders falsy value', async () => { render(<BooleanCell />); expect(screen.getByText(BOOL_FALSE_DISPLAY)).toBeInTheDocument(); });
7,044
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/ButtonCell/ButtonCell.test.tsx
/** * 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 ButtonCell from './index'; import { exampleRow } from '../fixtures'; test('renders with default props', async () => { const clickHandler = jest.fn(); const BUTTON_LABEL = 'Button Label'; render( <ButtonCell label={BUTTON_LABEL} key={5} index={0} row={exampleRow} onClick={clickHandler} />, ); await userEvent.click(screen.getByText(BUTTON_LABEL)); expect(clickHandler).toHaveBeenCalled(); });
7,047
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/NullCell/NullCell.test.tsx
/** * 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 { supersetTheme } from '@superset-ui/core'; import { NULL_DISPLAY } from 'src/constants'; import NullCell from '.'; test('renders null value', async () => { render(<NullCell />); expect(screen.getByText(NULL_DISPLAY)).toBeInTheDocument(); }); test('renders with gray font', async () => { render(<NullCell />); expect(screen.getByText(NULL_DISPLAY)).toHaveStyle( `color: ${supersetTheme.colors.grayscale.light1}`, ); });
7,050
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/NumericCell/NumericCell.test.tsx
/** * 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 NumericCell, { CurrencyCode, LocaleCode, Style } from './index'; test('renders with French locale and Euro currency format', () => { render( <NumericCell value={5678943} locale={LocaleCode.fr} options={{ style: Style.CURRENCY, currency: CurrencyCode.EUR, }} />, ); expect(screen.getByText('5 678 943,00 €')).toBeInTheDocument(); }); test('renders with English US locale and USD currency format', () => { render( <NumericCell value={5678943} locale={LocaleCode.en_US} options={{ style: Style.CURRENCY, currency: CurrencyCode.USD, }} />, ); expect(screen.getByText('$5,678,943.00')).toBeInTheDocument(); });
7,053
0
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers
petrpan-code/apache/superset/superset-frontend/src/components/Table/cell-renderers/TimeCell/TimeCell.test.tsx
/** * 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 { TimeFormats } from '@superset-ui/core'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import TimeCell from '.'; const DATE = Date.parse('2022-01-01'); test('renders with default format', async () => { render(<TimeCell value={DATE} />); expect(screen.getByText('2022-01-01 00:00:00')).toBeInTheDocument(); }); test('renders with custom format', async () => { render(<TimeCell value={DATE} format={TimeFormats.DATABASE_DATE} />); expect(screen.getByText('2022-01-01')).toBeInTheDocument(); }); test('renders with number', async () => { render(<TimeCell value={DATE.valueOf()} />); expect(screen.getByText('2022-01-01 00:00:00')).toBeInTheDocument(); }); test('renders with no value', async () => { render(<TimeCell />); expect(screen.getByText('N/A')).toBeInTheDocument(); }); test('renders with invalid date format', async () => { render(<TimeCell format="aaa-bbb-ccc" value={DATE} />); expect(screen.getByText('aaa-bbb-ccc')).toBeInTheDocument(); });
7,057
0
petrpan-code/apache/superset/superset-frontend/src/components/Table
petrpan-code/apache/superset/superset-frontend/src/components/Table/utils/utils.test.ts
/** * 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 { withinRange } from './utils'; test('withinRange supported positive numbers', () => { // Valid inputs within range expect(withinRange(50, 60, 16)).toBeTruthy(); // Valid inputs outside of range expect(withinRange(40, 60, 16)).toBeFalsy(); }); test('withinRange unsupported negative numbers', () => { // Negative numbers not supported expect(withinRange(65, 60, -16)).toBeFalsy(); expect(withinRange(-60, -65, 16)).toBeFalsy(); expect(withinRange(-60, -65, 16)).toBeFalsy(); expect(withinRange(-60, 65, 16)).toBeFalsy(); }); test('withinRange invalid inputs', () => { // Invalid inputs should return falsy and not throw an error // We need ts-ignore here to be able to pass invalid values and pass linting // @ts-ignore expect(withinRange(null, 60, undefined)).toBeFalsy(); // @ts-ignore expect(withinRange([], 'hello', {})).toBeFalsy(); // @ts-ignore expect(withinRange([], undefined, {})).toBeFalsy(); // @ts-ignore expect(withinRange([], 'hello', {})).toBeFalsy(); });
7,059
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TableCollection/TableCollection.test.tsx
/** * 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 { renderHook } from '@testing-library/react-hooks'; import { TableInstance, useTable } from 'react-table'; import TableCollection from '.'; let defaultProps: any; let tableHook: TableInstance<any>; beforeEach(() => { const columns = [ { Header: 'Column 1', accessor: 'col1', }, { Header: 'Column 2', accessor: 'col2', }, ]; const data = [ { col1: 'Line 01 - Col 01', col2: 'Line 01 - Col 02', }, { col1: 'Line 02 - Col 01', col2: 'Line 02 - Col 02', }, { col1: 'Line 03 - Col 01', col2: 'Line 03 - Col 02', }, ]; // @ts-ignore const tableHookResult = renderHook(() => useTable({ columns, data })); tableHook = tableHookResult.result.current; defaultProps = { prepareRow: tableHook.prepareRow, headerGroups: tableHook.headerGroups, rows: tableHook.rows, columns: tableHook.columns, loading: false, highlightRowId: 1, getTableProps: jest.fn(), getTableBodyProps: jest.fn(), }; }); test('Should headers visible', () => { render(<TableCollection {...defaultProps} />); expect(screen.getByRole('columnheader', { name: 'Column 1' })).toBeVisible(); expect(screen.getByRole('columnheader', { name: 'Column 2' })).toBeVisible(); }); test('Should the body visible', () => { render(<TableCollection {...defaultProps} />); expect(screen.getByText('Line 01 - Col 01')).toBeVisible(); expect(screen.getByText('Line 01 - Col 02')).toBeVisible(); expect(screen.getByText('Line 02 - Col 01')).toBeVisible(); expect(screen.getByText('Line 02 - Col 02')).toBeVisible(); expect(screen.getByText('Line 03 - Col 01')).toBeVisible(); expect(screen.getByText('Line 03 - Col 02')).toBeVisible(); }); test('Should the body content not be visible during loading', () => { render(<TableCollection {...defaultProps} loading />); expect(screen.getByText('Line 01 - Col 01')).toBeInTheDocument(); expect(screen.getByText('Line 01 - Col 01')).not.toBeVisible(); expect(screen.getByText('Line 01 - Col 02')).toBeInTheDocument(); expect(screen.getByText('Line 01 - Col 02')).not.toBeVisible(); expect(screen.getByText('Line 02 - Col 01')).toBeInTheDocument(); expect(screen.getByText('Line 02 - Col 01')).not.toBeVisible(); expect(screen.getByText('Line 02 - Col 02')).toBeInTheDocument(); expect(screen.getByText('Line 02 - Col 02')).not.toBeVisible(); expect(screen.getByText('Line 03 - Col 01')).toBeInTheDocument(); expect(screen.getByText('Line 03 - Col 01')).not.toBeVisible(); expect(screen.getByText('Line 03 - Col 02')).toBeInTheDocument(); expect(screen.getByText('Line 03 - Col 02')).not.toBeVisible(); }); test('Should the loading bar be visible during loading', () => { render(<TableCollection {...defaultProps} loading />); expect(screen.getAllByRole('progressbar')).toHaveLength(6); screen .getAllByRole('progressbar') .forEach(progressbar => expect(progressbar).toBeVisible()); });
7,061
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TableLoader/TableLoader.test.tsx
/** * 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 { Provider } from 'react-redux'; import fetchMock from 'fetch-mock'; import { storeWithState } from 'spec/fixtures/mockStore'; import ToastContainer from 'src/components/MessageToasts/ToastContainer'; import TableLoader, { TableLoaderProps } from '.'; const NO_DATA_TEXT = 'No data available'; const MOCK_GLOB = 'glob:*/api/v1/mock'; fetchMock.get(MOCK_GLOB, [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }, ]); const defaultProps: TableLoaderProps = { dataEndpoint: '/api/v1/mock', addDangerToast: jest.fn(), noDataText: NO_DATA_TEXT, }; function renderWithProps(props: TableLoaderProps = defaultProps) { return render( <Provider store={storeWithState({})}> <TableLoader {...props} /> <ToastContainer /> </Provider>, ); } test('renders loading and table', async () => { renderWithProps(); expect(screen.getByRole('status')).toBeInTheDocument(); expect(await screen.findByRole('table')).toBeInTheDocument(); }); test('renders with column names', async () => { renderWithProps({ ...defaultProps, columns: ['id_modified', 'name_modified'], }); const columnHeaders = await screen.findAllByRole('columnheader'); expect(columnHeaders[0]).toHaveTextContent('id_modified'); expect(columnHeaders[1]).toHaveTextContent('name_modified'); }); test('renders without mutator', async () => { renderWithProps(); expect(await screen.findAllByRole('row')).toHaveLength(3); expect(await screen.findAllByRole('columnheader')).toHaveLength(2); expect(await screen.findAllByRole('cell')).toHaveLength(4); }); test('renders with mutator', async () => { const mutator = function (data: { id: number; name: string }[]) { return data.map(row => ({ id: row.id, name: <h4>{row.name}</h4>, })); }; renderWithProps({ ...defaultProps, mutator }); expect(await screen.findAllByRole('heading', { level: 4 })).toHaveLength(2); }); test('renders empty message', async () => { fetchMock.mock(MOCK_GLOB, [], { overwriteRoutes: true, }); renderWithProps(); expect(await screen.findByText('No data available')).toBeInTheDocument(); }); test('renders blocked message', async () => { fetchMock.mock(MOCK_GLOB, 403, { overwriteRoutes: true, }); renderWithProps(); expect( await screen.findByText('Access to user activity data is restricted'), ).toBeInTheDocument(); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }); test('renders error message', async () => { fetchMock.mock(MOCK_GLOB, 500, { overwriteRoutes: true, }); renderWithProps(); expect(await screen.findByText(NO_DATA_TEXT)).toBeInTheDocument(); expect(await screen.findByRole('alert')).toBeInTheDocument(); });
7,063
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TableSelector/TableSelector.test.tsx
/** * 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 { act } from 'react-dom/test-utils'; import { render, screen, waitFor, within, defaultStore as store, } from 'spec/helpers/testing-library'; import { api } from 'src/hooks/apiResources/queryApi'; import fetchMock from 'fetch-mock'; import userEvent from '@testing-library/user-event'; import TableSelector, { TableSelectorMultiple } from '.'; const createProps = (props = {}) => ({ database: { id: 1, database_name: 'main', backend: 'sqlite', }, schema: 'test_schema', handleError: jest.fn(), ...props, }); const getTableMockFunction = () => ({ count: 4, result: [ { label: 'table_a', value: 'table_a' }, { label: 'table_b', value: 'table_b' }, { label: 'table_c', value: 'table_c' }, { label: 'table_d', value: 'table_d' }, ], } as any); const databaseApiRoute = 'glob:*/api/v1/database/?*'; const schemaApiRoute = 'glob:*/api/v1/database/*/schemas/?*'; const tablesApiRoute = 'glob:*/api/v1/database/*/tables/*'; const getSelectItemContainer = (select: HTMLElement) => select.parentElement?.parentElement?.getElementsByClassName( 'ant-select-selection-item', ); beforeEach(() => { fetchMock.get(databaseApiRoute, { result: [] }); }); afterEach(() => { act(() => { store.dispatch(api.util.resetApiState()); }); fetchMock.reset(); }); test('renders with default props', async () => { fetchMock.get(schemaApiRoute, { result: [] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const props = createProps(); render(<TableSelector {...props} />, { useRedux: true, store }); const databaseSelect = screen.getByRole('combobox', { name: 'Select database or type to search databases', }); const schemaSelect = screen.getByRole('combobox', { name: 'Select schema or type to search schemas', }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); await waitFor(() => { expect(databaseSelect).toBeInTheDocument(); expect(schemaSelect).toBeInTheDocument(); expect(tableSelect).toBeInTheDocument(); }); }); test('skips select all options', async () => { fetchMock.get(schemaApiRoute, { result: ['test_schema'] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const props = createProps(); render(<TableSelector {...props} tableSelectMode="multiple" />, { useRedux: true, store, }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); userEvent.click(tableSelect); expect( await screen.findByRole('option', { name: 'table_a' }), ).toBeInTheDocument(); expect(screen.queryByRole('option', { name: /Select All/i })).toBeFalsy(); }); test('renders table options without Select All option', async () => { fetchMock.get(schemaApiRoute, { result: ['test_schema'] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const props = createProps(); render(<TableSelector {...props} />, { useRedux: true, store }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); userEvent.click(tableSelect); expect( await screen.findByRole('option', { name: 'table_a' }), ).toBeInTheDocument(); expect( await screen.findByRole('option', { name: 'table_b' }), ).toBeInTheDocument(); }); test('renders disabled without schema', async () => { fetchMock.get(schemaApiRoute, { result: [] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const props = createProps(); render(<TableSelector {...props} schema={undefined} />, { useRedux: true, store, }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); await waitFor(() => { expect(tableSelect).toBeDisabled(); }); }); test('table select retain value if not in SQL Lab mode', async () => { fetchMock.get(schemaApiRoute, { result: ['test_schema'] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const callback = jest.fn(); const props = createProps({ onTableSelectChange: callback, sqlLabMode: false, }); render(<TableSelector {...props} />, { useRedux: true, store }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); expect(screen.queryByText('table_a')).not.toBeInTheDocument(); expect(getSelectItemContainer(tableSelect)).toHaveLength(0); userEvent.click(tableSelect); expect( await screen.findByRole('option', { name: 'table_a' }), ).toBeInTheDocument(); await waitFor(() => { userEvent.click(screen.getAllByText('table_a')[1]); }); expect(callback).toHaveBeenCalled(); const selectedValueContainer = getSelectItemContainer(tableSelect); expect(selectedValueContainer).toHaveLength(1); expect( await within(selectedValueContainer?.[0] as HTMLElement).findByText( 'table_a', ), ).toBeInTheDocument(); }); test('table multi select retain all the values selected', async () => { fetchMock.get(schemaApiRoute, { result: ['test_schema'] }); fetchMock.get(tablesApiRoute, getTableMockFunction()); const callback = jest.fn(); const props = createProps({ onTableSelectChange: callback, }); render(<TableSelectorMultiple {...props} />, { useRedux: true, store }); const tableSelect = screen.getByRole('combobox', { name: 'Select table or type to search tables', }); expect(screen.queryByText('table_a')).not.toBeInTheDocument(); expect(getSelectItemContainer(tableSelect)).toHaveLength(0); userEvent.click(tableSelect); await waitFor(async () => { const item = await screen.findAllByText('table_b'); userEvent.click(item[item.length - 1]); }); await waitFor(async () => { const item = await screen.findAllByText('table_c'); userEvent.click(item[item.length - 1]); }); const selection1 = await screen.findByRole('option', { name: 'table_b' }); expect(selection1).toHaveAttribute('aria-selected', 'true'); const selection2 = await screen.findByRole('option', { name: 'table_c' }); expect(selection2).toHaveAttribute('aria-selected', 'true'); });
7,066
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TableView/TableView.test.tsx
/** * 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 TableView, { TableViewProps } from '.'; const mockedProps: TableViewProps = { columns: [ { accessor: 'id', Header: 'ID', sortable: true, }, { accessor: 'age', Header: 'Age', }, { accessor: 'name', Header: 'Name', }, ], data: [ { id: 123, age: 27, name: 'Emily' }, { id: 321, age: 10, name: 'Kate' }, ], pageSize: 1, }; test('should render', () => { const { container } = render(<TableView {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render a table', () => { render(<TableView {...mockedProps} />); expect(screen.getByRole('table')).toBeInTheDocument(); }); test('should render the headers', () => { render(<TableView {...mockedProps} />); expect(screen.getAllByRole('columnheader')).toHaveLength(3); expect(screen.getByText('ID')).toBeInTheDocument(); expect(screen.getByText('Age')).toBeInTheDocument(); expect(screen.getByText('Name')).toBeInTheDocument(); }); test('should render the rows', () => { render(<TableView {...mockedProps} />); expect(screen.getAllByRole('row')).toHaveLength(2); }); test('should render the cells', () => { render(<TableView {...mockedProps} />); expect(screen.getAllByRole('cell')).toHaveLength(3); expect(screen.getByText('123')).toBeInTheDocument(); expect(screen.getByText('27')).toBeInTheDocument(); expect(screen.getByText('Emily')).toBeInTheDocument(); }); test('should render the pagination', () => { render(<TableView {...mockedProps} />); expect(screen.getByRole('navigation')).toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(4); expect(screen.getByText('«')).toBeInTheDocument(); expect(screen.getByText('»')).toBeInTheDocument(); }); test('should show the row count by default', () => { render(<TableView {...mockedProps} />); expect(screen.getByText('1-1 of 2')).toBeInTheDocument(); }); test('should NOT show the row count', () => { const noRowCountProps = { ...mockedProps, showRowCount: false, }; render(<TableView {...noRowCountProps} />); expect(screen.queryByText('1-1 of 2')).not.toBeInTheDocument(); }); test('should NOT render the pagination when disabled', () => { const withoutPaginationProps = { ...mockedProps, withPagination: false, }; render(<TableView {...withoutPaginationProps} />); expect(screen.queryByRole('navigation')).not.toBeInTheDocument(); }); test('should NOT render the pagination when fewer rows than page size', () => { const withoutPaginationProps = { ...mockedProps, pageSize: 3, }; render(<TableView {...withoutPaginationProps} />); expect(screen.queryByRole('navigation')).not.toBeInTheDocument(); }); test('should change page when « and » buttons are clicked', () => { render(<TableView {...mockedProps} />); const nextBtn = screen.getByText('»'); const prevBtn = screen.getByText('«'); userEvent.click(nextBtn); expect(screen.getAllByRole('cell')).toHaveLength(3); expect(screen.getByText('321')).toBeInTheDocument(); expect(screen.getByText('10')).toBeInTheDocument(); expect(screen.getByText('Kate')).toBeInTheDocument(); expect(screen.queryByText('Emily')).not.toBeInTheDocument(); userEvent.click(prevBtn); expect(screen.getAllByRole('cell')).toHaveLength(3); expect(screen.getByText('123')).toBeInTheDocument(); expect(screen.getByText('27')).toBeInTheDocument(); expect(screen.getByText('Emily')).toBeInTheDocument(); expect(screen.queryByText('Kate')).not.toBeInTheDocument(); }); test('should sort by age', () => { render(<TableView {...mockedProps} />); const ageSort = screen.getAllByRole('columnheader')[1]; userEvent.click(ageSort); expect(screen.getAllByRole('cell')[1]).toHaveTextContent('10'); userEvent.click(ageSort); expect(screen.getAllByRole('cell')[1]).toHaveTextContent('27'); }); test('should sort by initialSortBy DESC', () => { const initialSortByDescProps = { ...mockedProps, initialSortBy: [{ id: 'name', desc: true }], }; render(<TableView {...initialSortByDescProps} />); expect(screen.getByText('Kate')).toBeInTheDocument(); expect(screen.queryByText('Emily')).not.toBeInTheDocument(); }); test('should sort by initialSortBy ASC', () => { const initialSortByAscProps = { ...mockedProps, initialSortBy: [{ id: 'name', desc: false }], }; render(<TableView {...initialSortByAscProps} />); expect(screen.getByText('Emily')).toBeInTheDocument(); expect(screen.queryByText('Kate')).not.toBeInTheDocument(); }); test('should show empty', () => { const noDataProps = { ...mockedProps, data: [], noDataText: 'No data here', }; render(<TableView {...noDataProps} />); expect(screen.getByText('No data here')).toBeInTheDocument(); }); test('should render the right page', () => { const pageIndexProps = { ...mockedProps, initialPageIndex: 1, }; render(<TableView {...pageIndexProps} />); expect(screen.getByText('321')).toBeInTheDocument(); expect(screen.getByText('10')).toBeInTheDocument(); expect(screen.getByText('Kate')).toBeInTheDocument(); expect(screen.queryByText('Emily')).not.toBeInTheDocument(); }); test('should render the right wrap content text by columnsForWrapText', () => { const props = { ...mockedProps, columnsForWrapText: ['Name'], }; render(<TableView {...props} />); expect(screen.getAllByTestId('table-row-cell')[0]).toHaveClass( 'table-cell__nowrap', ); expect(screen.getAllByTestId('table-row-cell')[1]).toHaveClass( 'table-cell__nowrap', ); expect(screen.getAllByTestId('table-row-cell')[2]).toHaveClass( 'table-cell__wrap', ); });
7,073
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Tags/Tag.test.tsx
/** * 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 } from 'spec/helpers/testing-library'; import { screen } from '@testing-library/react'; import TagType from 'src/types/TagType'; import Tag from './Tag'; const mockedProps: TagType = { name: 'example-tag', id: 1, onDelete: undefined, editable: false, onClick: undefined, }; test('should render', () => { const { container } = render(<Tag {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render shortname properly', () => { const { container } = render(<Tag {...mockedProps} />); expect(container).toBeInTheDocument(); expect(screen.getByTestId('tag')).toBeInTheDocument(); expect(screen.getByTestId('tag')).toHaveTextContent(mockedProps.name); }); test('should render longname properly', () => { const longNameProps = { ...mockedProps, name: 'very-long-tag-name-that-truncates', }; const { container } = render(<Tag {...longNameProps} />); expect(container).toBeInTheDocument(); expect(screen.getByTestId('tag')).toBeInTheDocument(); expect(screen.getByTestId('tag')).toHaveTextContent( `${longNameProps.name.slice(0, 20)}...`, ); });
7,076
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Tags/TagsList.test.tsx
/** * 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, waitFor } from 'spec/helpers/testing-library'; import TagsList, { TagsListProps } from './TagsList'; const testTags = [ { name: 'example-tag1', id: 1, }, { name: 'example-tag2', id: 2, }, { name: 'example-tag3', id: 3, }, { name: 'example-tag4', id: 4, }, { name: 'example-tag5', id: 5, }, ]; const mockedProps: TagsListProps = { tags: testTags, onDelete: undefined, maxTags: 5, }; const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const findAllTags = () => waitFor(() => getElementsByClassName('.ant-tag')); test('should render', () => { const { container } = render(<TagsList {...mockedProps} />); expect(container).toBeInTheDocument(); }); test('should render 5 elements', async () => { render(<TagsList {...mockedProps} />); const tagsListItems = await findAllTags(); expect(tagsListItems).toHaveLength(5); expect(tagsListItems[0]).toHaveTextContent(testTags[0].name); expect(tagsListItems[1]).toHaveTextContent(testTags[1].name); expect(tagsListItems[2]).toHaveTextContent(testTags[2].name); expect(tagsListItems[3]).toHaveTextContent(testTags[3].name); expect(tagsListItems[4]).toHaveTextContent(testTags[4].name); }); test('should render 3 elements when maxTags is set to 3', async () => { render(<TagsList {...mockedProps} maxTags={3} />); const tagsListItems = await findAllTags(); expect(tagsListItems).toHaveLength(3); expect(tagsListItems[2]).toHaveTextContent('+3...'); });
7,079
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Tags/utils.test.tsx
import { tagToSelectOption } from 'src/components/Tags/utils'; describe('tagToSelectOption', () => { test('converts a Tag object with table_name to a SelectTagsValue', () => { const tag = { id: '1', name: 'TagName', table_name: 'Table1', }; const expectedSelectTagsValue = { value: 'TagName', label: 'TagName', key: '1', }; expect(tagToSelectOption(tag)).toEqual(expectedSelectTagsValue); }); });
7,082
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Timer/Timer.test.tsx
/** * @jest-environment jsdom */ /** * 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, sleep, waitFor } from 'spec/helpers/testing-library'; import Timer, { TimerProps } from 'src/components/Timer'; import { now } from 'src/utils/dates'; function parseTime(text?: string | null) { return !!text && Number(text.replace(/:/g, '')); } describe('Timer', () => { const mockProps: TimerProps = { startTime: now(), endTime: undefined, isRunning: true, status: 'warning', }; it('should render correctly', async () => { const screen = render(<Timer {...mockProps} />); const node = screen.getByRole('timer'); let text = node.textContent || ''; expect(node).toBeInTheDocument(); expect(node).toHaveTextContent('00:00:00.00'); // should start running await waitFor(() => { expect(parseTime(screen.getByRole('timer')?.textContent)).toBeGreaterThan( 0.2, ); }); text = node.textContent || ''; // should stop screen.rerender(<Timer {...mockProps} isRunning={false} />); // the same node should still be in DOM and the content should not change expect(screen.getByRole('timer')).toBe(node); expect(node).toHaveTextContent(text); // the timestamp should not change even after while await sleep(100); expect(screen.getByRole('timer')).toBe(node); expect(node).toHaveTextContent(text); // should continue and start from stopped time screen.rerender(<Timer {...mockProps} isRunning />); expect(screen.getByRole('timer')).toBe(node); expect(node).toHaveTextContent(text); await waitFor(() => { expect(screen.getByRole('timer')).toBe(node); expect(parseTime(node.textContent)).toBeGreaterThan(0.3); }); // should restart from start screen.rerender(<Timer {...mockProps} startTime={now()} />); await waitFor(() => { expect(parseTime(node.textContent)).toBeLessThan(0.1); }); // should continue to run await waitFor(() => { expect(parseTime(node.textContent)).toBeGreaterThan(0.3); }); }); });
7,085
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TimezoneSelector/TimezoneSelector.test.tsx
/** * 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 moment from 'moment-timezone'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import type { TimezoneSelectorProps } from './index'; const loadComponent = (mockCurrentTime?: string) => { if (mockCurrentTime) { jest.useFakeTimers('modern'); jest.setSystemTime(new Date(mockCurrentTime)); } return new Promise<React.FC<TimezoneSelectorProps>>(resolve => { jest.isolateModules(() => { const { default: TimezoneSelector } = module.require('./index'); resolve(TimezoneSelector); jest.useRealTimers(); }); }); }; const getSelectOptions = () => waitFor(() => document.querySelectorAll('.ant-select-item-option-content')); const openSelectMenu = () => { const searchInput = screen.getByRole('combobox'); userEvent.click(searchInput); }; jest.spyOn(moment.tz, 'guess').mockReturnValue('America/New_York'); test('use the timezone from `moment` if no timezone provided', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); render(<TimezoneSelector onTimezoneChange={onTimezoneChange} />); expect(onTimezoneChange).toHaveBeenCalledTimes(1); expect(onTimezoneChange).toHaveBeenCalledWith('America/Nassau'); }); test('update to closest deduped timezone when timezone is provided', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="America/Los_Angeles" />, ); expect(onTimezoneChange).toHaveBeenCalledTimes(1); expect(onTimezoneChange).toHaveBeenLastCalledWith('America/Vancouver'); }); test('use the default timezone when an invalid timezone is provided', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="UTC" />, ); expect(onTimezoneChange).toHaveBeenCalledTimes(1); expect(onTimezoneChange).toHaveBeenLastCalledWith('Africa/Abidjan'); }); test('render timezones in correct oder for standard time', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="America/Nassau" />, ); openSelectMenu(); const options = await getSelectOptions(); expect(options[0]).toHaveTextContent('GMT -05:00 (Eastern Standard Time)'); expect(options[1]).toHaveTextContent('GMT -11:00 (Pacific/Pago_Pago)'); expect(options[2]).toHaveTextContent('GMT -10:00 (Hawaii Standard Time)'); expect(options[3]).toHaveTextContent('GMT -10:00 (America/Adak)'); }); test('render timezones in correct order for daylight saving time', async () => { const TimezoneSelector = await loadComponent('2022-07-01'); const onTimezoneChange = jest.fn(); render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="America/Nassau" />, ); openSelectMenu(); const options = await getSelectOptions(); // first option is always current timezone expect(options[0]).toHaveTextContent('GMT -04:00 (Eastern Daylight Time)'); expect(options[1]).toHaveTextContent('GMT -11:00 (Pacific/Pago_Pago)'); expect(options[2]).toHaveTextContent('GMT -10:00 (Hawaii Standard Time)'); expect(options[3]).toHaveTextContent('GMT -09:30 (Pacific/Marquesas)'); }); test('can select a timezone values and returns canonical timezone name', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="Africa/Abidjan" />, ); openSelectMenu(); const searchInput = screen.getByRole('combobox'); // search for mountain time await userEvent.type(searchInput, 'mou', { delay: 10 }); const findTitle = 'GMT -07:00 (Mountain Standard Time)'; const selectOption = await screen.findByTitle(findTitle); userEvent.click(selectOption); expect(onTimezoneChange).toHaveBeenCalledTimes(1); expect(onTimezoneChange).toHaveBeenLastCalledWith('America/Cambridge_Bay'); }); test('can update props and rerender with different values', async () => { const TimezoneSelector = await loadComponent('2022-01-01'); const onTimezoneChange = jest.fn(); const { rerender } = render( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="Asia/Dubai" />, ); expect(screen.getByTitle('GMT +04:00 (Asia/Dubai)')).toBeInTheDocument(); rerender( <TimezoneSelector onTimezoneChange={onTimezoneChange} timezone="Australia/Perth" />, ); expect(screen.getByTitle('GMT +08:00 (Australia/Perth)')).toBeInTheDocument(); expect(onTimezoneChange).toHaveBeenCalledTimes(0); });
7,088
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/Tooltip/Tooltip.test.tsx
/** * 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 { supersetTheme } from '@superset-ui/core'; import Button from 'src/components/Button'; import Icons from 'src/components/Icons'; import { Tooltip } from '.'; test('starts hidden with default props', () => { render( <Tooltip title="Simple tooltip"> <Button>Hover me</Button> </Tooltip>, ); expect(screen.queryByRole('tooltip')).not.toBeInTheDocument(); }); test('renders on hover', async () => { render( <Tooltip title="Simple tooltip"> <Button>Hover me</Button> </Tooltip>, ); userEvent.hover(screen.getByRole('button')); expect(await screen.findByRole('tooltip')).toBeInTheDocument(); }); test('renders with theme', () => { render( <Tooltip title="Simple tooltip" defaultVisible> <Button>Hover me</Button> </Tooltip>, ); const tooltip = screen.getByRole('tooltip'); expect(tooltip).toHaveStyle({ background: `${supersetTheme.colors.grayscale.dark2}e6`, }); expect(tooltip.parentNode?.parentNode).toHaveStyle({ lineHeight: 1.6, fontSize: 12, }); }); test('renders with icon child', async () => { render( <Tooltip title="Simple tooltip"> <Icons.Alert>Hover me</Icons.Alert> </Tooltip>, ); userEvent.hover(screen.getByRole('img')); expect(await screen.findByRole('tooltip')).toBeInTheDocument(); });
7,091
0
petrpan-code/apache/superset/superset-frontend/src/components
petrpan-code/apache/superset/superset-frontend/src/components/TooltipParagraph/TooltipParagraph.test.tsx
/** * 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 TooltipParagraph from '.'; test('starts hidden with default props', () => { render(<TooltipParagraph>This is tootlip description.</TooltipParagraph>); expect(screen.queryByRole('tooltip')).not.toBeInTheDocument(); }); test('not render on hover when not truncated', async () => { const { container } = render( <div style={{ width: '200px' }}> <TooltipParagraph> <span data-test="test-text">This is short</span> </TooltipParagraph> </div>, ); userEvent.hover(screen.getByTestId('test-text')); await waitFor(() => expect(container.firstChild?.firstChild).not.toHaveClass( 'ant-tooltip-open', ), ); }); test('render on hover when truncated', async () => { const { container } = render( <div style={{ width: '200px' }}> <TooltipParagraph> <span data-test="test-text">This is too long and should truncate.</span> </TooltipParagraph> </div>, ); userEvent.hover(screen.getByTestId('test-text')); await waitFor(() => expect(container.firstChild?.firstChild).toHaveClass('ant-tooltip-open'), ); });
7,120
0
petrpan-code/apache/superset/superset-frontend/src/dashboard
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/MissingChart.test.tsx
/** * 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 } from 'spec/helpers/testing-library'; import MissingChart from 'src/dashboard/components/MissingChart'; type MissingChartProps = { height: number; }; const setup = (overrides?: MissingChartProps) => ( <MissingChart height={100} {...overrides} /> ); describe('MissingChart', () => { it('renders a .missing-chart-container', () => { const rendered = render(setup()); const missingChartContainer = rendered.container.querySelector( '.missing-chart-container', ); expect(missingChartContainer).toBeVisible(); }); it('renders a .missing-chart-body', () => { const rendered = render(setup()); const missingChartBody = rendered.container.querySelector( '.missing-chart-body', ); const bodyText = 'There is no chart definition associated with this component, could it have been deleted?<br><br>Delete this container and save to remove this message.'; expect(missingChartBody).toBeVisible(); expect(missingChartBody?.innerHTML).toMatch(bodyText); }); });
7,121
0
petrpan-code/apache/superset/superset-frontend/src/dashboard
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/RefreshIntervalModal.test.tsx
/** * 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 { mount } from 'enzyme'; import { render, screen } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import fetchMock from 'fetch-mock'; import ModalTrigger from 'src/components/ModalTrigger'; import RefreshIntervalModal from 'src/dashboard/components/RefreshIntervalModal'; import HeaderActionsDropdown from 'src/dashboard/components/Header/HeaderActionsDropdown'; import Alert from 'src/components/Alert'; import { supersetTheme, ThemeProvider } from '@superset-ui/core'; describe('RefreshIntervalModal - Enzyme', () => { const getMountWrapper = (props: any) => mount(<RefreshIntervalModal {...props} />, { wrappingComponent: ThemeProvider, wrappingComponentProps: { theme: supersetTheme, }, }); const mockedProps = { triggerNode: <i className="fa fa-edit" />, refreshFrequency: 10, onChange: jest.fn(), editMode: true, refreshIntervalOptions: [], }; it('should show warning message', () => { const props = { ...mockedProps, refreshLimit: 3600, refreshWarning: 'Show warning', }; const wrapper = getMountWrapper(props); wrapper.find('span[role="button"]').simulate('click'); // @ts-ignore (for handleFrequencyChange) wrapper.instance().handleFrequencyChange(30); wrapper.update(); expect(wrapper.find(ModalTrigger).find(Alert)).toExist(); // @ts-ignore (for handleFrequencyChange) wrapper.instance().handleFrequencyChange(3601); wrapper.update(); expect(wrapper.find(ModalTrigger).find(Alert)).not.toExist(); wrapper.unmount(); }); }); const createProps = () => ({ addSuccessToast: jest.fn(), addDangerToast: jest.fn(), customCss: '.header-with-actions .right-button-panel .ant-dropdown-trigger{margin-left: 100px;}', dashboardId: 1, dashboardInfo: { id: 1, dash_edit_perm: true, dash_save_perm: true, userId: '1', metadata: {}, common: { conf: { DASHBOARD_AUTO_REFRESH_INTERVALS: [ [0, "Don't refresh"], [10, '10 seconds'], [30, '30 seconds'], [60, '1 minute'], [300, '5 minutes'], [1800, '30 minutes'], [3600, '1 hour'], [21600, '6 hours'], [43200, '12 hours'], [86400, '24 hours'], ], }, }, }, dashboardTitle: 'Title', editMode: false, expandedSlices: {}, forceRefreshAllCharts: jest.fn(), hasUnsavedChanges: false, isLoading: false, layout: {}, dataMask: {}, onChange: jest.fn(), onSave: jest.fn(), refreshFrequency: 0, setRefreshFrequency: jest.fn(), shouldPersistRefreshFrequency: false, showPropertiesModal: jest.fn(), startPeriodicRender: jest.fn(), updateCss: jest.fn(), userCanEdit: false, userCanSave: false, userCanShare: false, lastModifiedTime: 0, isDropdownVisible: true, }); const editModeOnProps = { ...createProps(), editMode: true, }; const setup = (overrides?: any) => ( <div className="dashboard-header"> <HeaderActionsDropdown {...editModeOnProps} {...overrides} /> </div> ); fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {}); const openRefreshIntervalModal = async () => { const autoRefreshOption = screen.getByText('Set auto-refresh interval'); userEvent.click(autoRefreshOption); }; const displayOptions = async () => { // Click default refresh interval option to display other options userEvent.click(screen.getByText(/don't refresh/i)); }; const defaultRefreshIntervalModalProps = { triggerNode: <i className="fa fa-edit" />, refreshFrequency: 0, onChange: jest.fn(), editMode: true, addSuccessToast: jest.fn(), refreshIntervalOptions: [], }; describe('RefreshIntervalModal - RTL', () => { it('is valid', () => { expect( React.isValidElement( <RefreshIntervalModal {...defaultRefreshIntervalModalProps} />, ), ).toBe(true); }); it('renders refresh interval modal', async () => { render(setup(editModeOnProps)); await openRefreshIntervalModal(); // Assert that modal exists by checking for the modal title expect(screen.getByText('Refresh interval')).toBeVisible(); }); it('renders refresh interval options', async () => { render(setup(editModeOnProps)); await openRefreshIntervalModal(); await displayOptions(); // Assert that both "Don't refresh" instances exist // - There will be two at this point, the default option and the dropdown option const dontRefreshInstances = screen.getAllByText(/don't refresh/i); expect(dontRefreshInstances).toHaveLength(2); dontRefreshInstances.forEach(option => { expect(option).toBeInTheDocument(); }); // Assert that all the other options exist const options = [ screen.getByText(/10 seconds/i), screen.getByText(/30 seconds/i), screen.getByText(/1 minute/i), screen.getByText(/5 minutes/i), screen.getByText(/30 minutes/i), screen.getByText(/1 hour/i), screen.getByText(/6 hours/i), screen.getByText(/12 hours/i), screen.getByText(/24 hours/i), ]; options.forEach(option => { expect(option).toBeInTheDocument(); }); }); it('should change selected value', async () => { render(setup(editModeOnProps)); await openRefreshIntervalModal(); // Initial selected value should be "Don't refresh" const selectedValue = screen.getByText(/don't refresh/i); expect(selectedValue.title).toMatch(/don't refresh/i); // Display options and select "10 seconds" await displayOptions(); userEvent.click(screen.getByText(/10 seconds/i)); // Selected value should now be "10 seconds" expect(selectedValue.title).toMatch(/10 seconds/i); expect(selectedValue.title).not.toMatch(/don't refresh/i); }); it('should save a newly-selected value', async () => { render(setup(editModeOnProps)); await openRefreshIntervalModal(); await displayOptions(); // Select a new interval and click save userEvent.click(screen.getByText(/10 seconds/i)); userEvent.click(screen.getByRole('button', { name: /save/i })); expect(editModeOnProps.setRefreshFrequency).toHaveBeenCalled(); expect(editModeOnProps.setRefreshFrequency).toHaveBeenCalledWith( 10, editModeOnProps.editMode, ); expect(editModeOnProps.addSuccessToast).toHaveBeenCalled(); }); it('should show warning message', async () => { // TODO (lyndsiWilliams): This test is incomplete const warningProps = { ...editModeOnProps, refreshLimit: 3600, refreshWarning: 'Show warning', }; render(setup(warningProps)); await openRefreshIntervalModal(); await displayOptions(); userEvent.click(screen.getByText(/30 seconds/i)); userEvent.click(screen.getByRole('button', { name: /save/i })); // screen.debug(screen.getByRole('alert')); expect.anything(); }); });
7,126
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/AddSliceCard/AddSliceCard.test.tsx
/** * 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 { FeatureFlag } from '@superset-ui/core'; import userEvent from '@testing-library/user-event'; import { act, render, screen, within } from 'spec/helpers/testing-library'; import AddSliceCard from '.'; jest.mock('src/components/DynamicPlugins', () => ({ usePluginContext: () => ({ mountedPluginMetadata: { table: { name: 'Table' } }, }), })); const mockedProps = { visType: 'table', sliceName: '-', }; declare const global: { featureFlags: Record<string, boolean>; }; test('do not render thumbnail if feature flag is not set', async () => { global.featureFlags = { [FeatureFlag.THUMBNAILS]: false, }; await act(async () => { render(<AddSliceCard {...mockedProps} />); }); expect(screen.queryByTestId('thumbnail')).not.toBeInTheDocument(); }); test('render thumbnail if feature flag is set', async () => { global.featureFlags = { [FeatureFlag.THUMBNAILS]: true, }; await act(async () => { render(<AddSliceCard {...mockedProps} />); }); expect(screen.queryByTestId('thumbnail')).toBeInTheDocument(); }); test('does not render the tooltip with anchors', async () => { const mock = jest .spyOn(React, 'useState') .mockImplementation(() => [true, jest.fn()]); render( <AddSliceCard {...mockedProps} datasourceUrl="http://test.com" datasourceName="datasource-name" />, ); userEvent.hover(screen.getByRole('link', { name: 'datasource-name' })); expect(await screen.findByRole('tooltip')).toBeInTheDocument(); const tooltip = await screen.findByRole('tooltip'); expect(within(tooltip).queryByRole('link')).not.toBeInTheDocument(); mock.mockRestore(); });
7,130
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/AnchorLink/AnchorLink.test.tsx
/** * 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, act } from 'spec/helpers/testing-library'; import AnchorLink from 'src/dashboard/components/AnchorLink'; describe('AnchorLink', () => { const props = { id: 'CHART-123', dashboardId: 10, }; const globalLocation = window.location; afterEach(() => { window.location = globalLocation; }); it('should scroll the AnchorLink into view upon mount if id matches hash', async () => { const callback = jest.fn(); jest.spyOn(document, 'getElementById').mockReturnValue({ scrollIntoView: callback, } as unknown as HTMLElement); window.location.hash = props.id; await act(async () => { render(<AnchorLink {...props} />, { useRedux: true }); }); expect(callback).toHaveBeenCalledTimes(1); window.location.hash = 'random'; await act(async () => { render(<AnchorLink {...props} />, { useRedux: true }); }); expect(callback).toHaveBeenCalledTimes(1); }); it('should render anchor link without short link button', () => { const { container, queryByRole } = render( <AnchorLink showShortLinkButton={false} {...props} />, { useRedux: true }, ); expect(container.querySelector(`#${props.id}`)).toBeInTheDocument(); expect(queryByRole('button')).toBe(null); }); it('should render short link button', () => { const { getByRole } = render( <AnchorLink {...props} showShortLinkButton />, { useRedux: true }, ); expect(getByRole('button')).toBeInTheDocument(); }); });
7,132
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/BuilderComponentPane/BuilderComponentPane.test.tsx
/** * 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 BuilderComponentPane from '.'; jest.mock('src/dashboard/containers/SliceAdder'); test('BuilderComponentPane has correct tabs in correct order', () => { render(<BuilderComponentPane topOffset={115} />); const tabs = screen.getAllByRole('tab'); expect(tabs).toHaveLength(2); expect(tabs[0]).toHaveTextContent('Charts'); expect(tabs[1]).toHaveTextContent('Layout elements'); expect(screen.getByRole('tab', { selected: true })).toHaveTextContent( 'Charts', ); });
7,134
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/CssEditor/CssEditor.test.tsx
/** * 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 { CssEditor as AceCssEditor } from 'src/components/AsyncAceEditor'; import { IAceEditorProps } from 'react-ace'; import userEvent from '@testing-library/user-event'; import CssEditor from '.'; jest.mock('src/components/AsyncAceEditor', () => ({ CssEditor: ({ value, onChange }: IAceEditorProps) => ( <textarea defaultValue={value} onChange={value => onChange?.(value.target.value)} /> ), })); const templates = [ { label: 'Template A', css: 'background-color: red;' }, { label: 'Template B', css: 'background-color: blue;' }, { label: 'Template C', css: 'background-color: yellow;' }, ]; AceCssEditor.preload = () => new Promise(() => {}); test('renders with default props', () => { render(<CssEditor triggerNode={<>Click</>} />); expect(screen.getByRole('button', { name: 'Click' })).toBeInTheDocument(); }); test('renders with initial CSS', () => { const initialCss = 'margin: 10px;'; render(<CssEditor triggerNode={<>Click</>} initialCss={initialCss} />); userEvent.click(screen.getByRole('button', { name: 'Click' })); expect(screen.getByText(initialCss)).toBeInTheDocument(); }); test('renders with templates', async () => { render(<CssEditor triggerNode={<>Click</>} templates={templates} />); userEvent.click(screen.getByRole('button', { name: 'Click' })); userEvent.hover(screen.getByText('Load a CSS template')); await waitFor(() => { templates.forEach(template => expect(screen.getByText(template.label)).toBeInTheDocument(), ); }); }); test('triggers onChange when using the editor', () => { const onChange = jest.fn(); const initialCss = 'margin: 10px;'; const additionalCss = 'color: red;'; render( <CssEditor triggerNode={<>Click</>} initialCss={initialCss} onChange={onChange} />, ); userEvent.click(screen.getByRole('button', { name: 'Click' })); expect(onChange).not.toHaveBeenCalled(); userEvent.type(screen.getByText(initialCss), additionalCss); expect(onChange).toHaveBeenLastCalledWith(initialCss.concat(additionalCss)); }); test('triggers onChange when selecting a template', async () => { const onChange = jest.fn(); render( <CssEditor triggerNode={<>Click</>} templates={templates} onChange={onChange} />, ); userEvent.click(screen.getByRole('button', { name: 'Click' })); userEvent.click(screen.getByText('Load a CSS template')); expect(onChange).not.toHaveBeenCalled(); userEvent.click(await screen.findByText('Template A')); expect(onChange).toHaveBeenCalledTimes(1); });
7,136
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/DashboardBuilder/DashboardBuilder.test.tsx
/** * 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 fetchMock from 'fetch-mock'; import { render } from 'spec/helpers/testing-library'; import { fireEvent, within } from '@testing-library/react'; import * as uiCore from '@superset-ui/core'; import DashboardBuilder from 'src/dashboard/components/DashboardBuilder/DashboardBuilder'; import useStoredSidebarWidth from 'src/components/ResizableSidebar/useStoredSidebarWidth'; import { fetchFaveStar, setActiveTabs, setDirectPathToChild, } from 'src/dashboard/actions/dashboardState'; import { dashboardLayout as undoableDashboardLayout, dashboardLayoutWithTabs as undoableDashboardLayoutWithTabs, } from 'spec/fixtures/mockDashboardLayout'; import { storeWithState } from 'spec/fixtures/mockStore'; import mockState from 'spec/fixtures/mockState'; import { DASHBOARD_ROOT_ID } from 'src/dashboard/util/constants'; fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {}); jest.mock('src/dashboard/actions/dashboardState', () => ({ ...jest.requireActual('src/dashboard/actions/dashboardState'), fetchFaveStar: jest.fn(), setActiveTabs: jest.fn(), setDirectPathToChild: jest.fn(), })); jest.mock('src/components/ResizableSidebar/useStoredSidebarWidth'); // mock following dependant components to fix the prop warnings jest.mock('src/components/DeprecatedSelect/WindowedSelect', () => () => ( <div data-test="mock-windowed-select" /> )); jest.mock('src/components/DeprecatedSelect', () => () => ( <div data-test="mock-deprecated-select" /> )); jest.mock('src/components/Select/Select', () => () => ( <div data-test="mock-select" /> )); jest.mock('src/components/Select/AsyncSelect', () => () => ( <div data-test="mock-async-select" /> )); jest.mock('src/dashboard/components/Header/HeaderActionsDropdown', () => () => ( <div data-test="mock-header-actions-dropdown" /> )); jest.mock('src/components/PageHeaderWithActions', () => ({ PageHeaderWithActions: () => ( <div data-test="mock-page-header-with-actions" /> ), })); jest.mock( 'src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigModal', () => () => <div data-test="mock-filters-config-modal" />, ); jest.mock('src/dashboard/components/BuilderComponentPane', () => () => ( <div data-test="mock-builder-component-pane" /> )); jest.mock('src/dashboard/components/nativeFilters/FilterBar', () => () => ( <div data-test="mock-filter-bar" /> )); jest.mock('src/dashboard/containers/DashboardGrid', () => () => ( <div data-test="mock-dashboard-grid" /> )); describe('DashboardBuilder', () => { let favStarStub: jest.Mock; let activeTabsStub: jest.Mock; beforeAll(() => { // this is invoked on mount, so we stub it instead of making a request favStarStub = (fetchFaveStar as jest.Mock).mockReturnValue({ type: 'mock-action', }); activeTabsStub = (setActiveTabs as jest.Mock).mockReturnValue({ type: 'mock-action', }); (useStoredSidebarWidth as jest.Mock).mockImplementation(() => [ 100, jest.fn(), ]); }); afterAll(() => { favStarStub.mockReset(); activeTabsStub.mockReset(); (useStoredSidebarWidth as jest.Mock).mockReset(); }); function setup(overrideState = {}) { return render(<DashboardBuilder />, { useRedux: true, store: storeWithState({ ...mockState, dashboardLayout: undoableDashboardLayout, ...overrideState, }), useDnd: true, }); } it('should render a StickyContainer with class "dashboard"', () => { const { getByTestId } = setup(); const stickyContainer = getByTestId('dashboard-content-wrapper'); expect(stickyContainer).toHaveClass('dashboard'); }); it('should add the "dashboard--editing" class if editMode=true', () => { const { getByTestId } = setup({ dashboardState: { ...mockState.dashboardState, editMode: true }, }); const stickyContainer = getByTestId('dashboard-content-wrapper'); expect(stickyContainer).toHaveClass('dashboard dashboard--editing'); }); it('should render a DragDroppable DashboardHeader', () => { const { queryByTestId } = setup(); const header = queryByTestId('dashboard-header-container'); expect(header).toBeTruthy(); }); it('should render a Sticky top-level Tabs if the dashboard has tabs', async () => { const { findAllByTestId } = setup({ dashboardLayout: undoableDashboardLayoutWithTabs, }); const sticky = await findAllByTestId('nav-list'); expect(sticky.length).toBe(1); expect(sticky[0]).toHaveAttribute('id', 'TABS_ID'); const dashboardTabComponents = within(sticky[0]).getAllByRole('tab'); const tabChildren = undoableDashboardLayoutWithTabs.present.TABS_ID.children; expect(dashboardTabComponents.length).toBe(tabChildren.length); tabChildren.forEach((tabId, i) => { const idMatcher = new RegExp(`${tabId}$`); expect(dashboardTabComponents[i]).toHaveAttribute( 'id', expect.stringMatching(idMatcher), ); }); }); it('should render one Tabs and two TabPane', async () => { const { findAllByRole } = setup({ dashboardLayout: undoableDashboardLayoutWithTabs, }); const tabs = await findAllByRole('tablist'); expect(tabs.length).toBe(1); const tabPanels = await findAllByRole('tabpanel'); expect(tabPanels.length).toBe(2); }); it('should render a TabPane and DashboardGrid for first Tab', async () => { const { findByTestId } = setup({ dashboardLayout: undoableDashboardLayoutWithTabs, }); const parentSize = await findByTestId('grid-container'); const expectedCount = undoableDashboardLayoutWithTabs.present.TABS_ID.children.length; const tabPanels = within(parentSize).getAllByRole('tabpanel', { // to include invisiable tab panels hidden: true, }); expect(tabPanels.length).toBe(expectedCount); expect( within(tabPanels[0]).getAllByTestId('mock-dashboard-grid').length, ).toBe(1); }); it('should render a TabPane and DashboardGrid for second Tab', async () => { const { findByTestId } = setup({ dashboardLayout: undoableDashboardLayoutWithTabs, dashboardState: { ...mockState.dashboardState, directPathToChild: [DASHBOARD_ROOT_ID, 'TABS_ID', 'TAB_ID2'], }, }); const parentSize = await findByTestId('grid-container'); const expectedCount = undoableDashboardLayoutWithTabs.present.TABS_ID.children.length; const tabPanels = within(parentSize).getAllByRole('tabpanel', { // to include invisiable tab panels hidden: true, }); expect(tabPanels.length).toBe(expectedCount); expect( within(tabPanels[1]).getAllByTestId('mock-dashboard-grid').length, ).toBe(1); }); it('should render a BuilderComponentPane if editMode=false and user selects "Insert Components" pane', () => { const { queryAllByTestId } = setup(); const builderComponents = queryAllByTestId('mock-builder-component-pane'); expect(builderComponents.length).toBe(0); }); it('should render a BuilderComponentPane if editMode=true and user selects "Insert Components" pane', () => { const { queryAllByTestId } = setup({ dashboardState: { editMode: true } }); const builderComponents = queryAllByTestId('mock-builder-component-pane'); expect(builderComponents.length).toBeGreaterThanOrEqual(1); }); it('should change redux state if a top-level Tab is clicked', async () => { (setDirectPathToChild as jest.Mock).mockImplementation(arg0 => ({ type: 'type', arg0, })); const { findByRole } = setup({ dashboardLayout: undoableDashboardLayoutWithTabs, }); const tabList = await findByRole('tablist'); const tabs = within(tabList).getAllByRole('tab'); expect(setDirectPathToChild).toHaveBeenCalledTimes(0); fireEvent.click(tabs[1]); expect(setDirectPathToChild).toHaveBeenCalledWith([ 'ROOT_ID', 'TABS_ID', 'TAB_ID2', ]); (setDirectPathToChild as jest.Mock).mockReset(); }); it('should not display a loading spinner when saving is not in progress', () => { const { queryByAltText } = setup(); expect(queryByAltText('Loading...')).not.toBeInTheDocument(); }); it('should display a loading spinner when saving is in progress', async () => { const { findByAltText } = setup({ dashboardState: { dashboardIsSaving: true }, }); expect(await findByAltText('Loading...')).toBeVisible(); }); describe('when nativeFiltersEnabled', () => { let isFeatureEnabledMock: jest.MockInstance<boolean, [string]>; beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation( flag => flag === uiCore.FeatureFlag.DASHBOARD_NATIVE_FILTERS, ); }); afterAll(() => { isFeatureEnabledMock.mockRestore(); }); it('should set FilterBar width by useStoredSidebarWidth', () => { const expectedValue = 200; const setter = jest.fn(); (useStoredSidebarWidth as jest.Mock).mockImplementation(() => [ expectedValue, setter, ]); const { getByTestId } = setup({ dashboardInfo: { ...mockState.dashboardInfo, dash_edit_perm: true, }, }); const filterbar = getByTestId('dashboard-filters-panel'); expect(filterbar).toHaveStyleRule('width', `${expectedValue}px`); }); }); });
7,141
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/FiltersBadge/FiltersBadge.test.tsx
/** * 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 { shallow } from 'enzyme'; import { Provider } from 'react-redux'; import { Store } from 'redux'; import * as SupersetUI from '@superset-ui/core'; import { styledMount as mount } from 'spec/helpers/theming'; import { CHART_RENDERING_SUCCEEDED, CHART_UPDATE_SUCCEEDED, } from 'src/components/Chart/chartAction'; import { buildActiveFilters } from 'src/dashboard/util/activeDashboardFilters'; import { FiltersBadge } from 'src/dashboard/components/FiltersBadge'; import { getMockStoreWithFilters, getMockStoreWithNativeFilters, } from 'spec/fixtures/mockStore'; import { sliceId } from 'spec/fixtures/mockChartQueries'; import { dashboardFilters } from 'spec/fixtures/mockDashboardFilters'; import { dashboardWithFilter } from 'spec/fixtures/mockDashboardLayout'; const defaultStore = getMockStoreWithFilters(); function setup(store: Store = defaultStore) { return mount( <Provider store={store}> <FiltersBadge chartId={sliceId} /> </Provider>, ); } describe('FiltersBadge', () => { // there's this bizarre "active filters" thing // that doesn't actually use any kind of state management. // Have to set variables in there. buildActiveFilters({ dashboardFilters, components: dashboardWithFilter, }); beforeEach(() => { // shallow rendering in enzyme doesn't propagate contexts correctly, // so we have to mock the hook. // See https://medium.com/7shifts-engineering-blog/testing-usecontext-react-hook-with-enzyme-shallow-da062140fc83 jest .spyOn(SupersetUI, 'useTheme') .mockImplementation(() => SupersetUI.supersetTheme); }); describe('for dashboard filters', () => { it("doesn't show number when there are no active filters", () => { const store = getMockStoreWithFilters(); // start with basic dashboard state, dispatch an event to simulate query completion store.dispatch({ type: CHART_UPDATE_SUCCEEDED, key: sliceId, queriesResponse: [ { status: 'success', applied_filters: [], rejected_filters: [], }, ], dashboardFilters, }); const wrapper = shallow( <Provider store={store}> <FiltersBadge chartId={sliceId} />, </Provider>, ); expect(wrapper.find('[data-test="applied-filter-count"]')).not.toExist(); }); it('shows the indicator when filters have been applied', () => { const store = getMockStoreWithFilters(); // start with basic dashboard state, dispatch an event to simulate query completion store.dispatch({ type: CHART_UPDATE_SUCCEEDED, key: sliceId, queriesResponse: [ { status: 'success', applied_filters: [{ column: 'region' }], rejected_filters: [], }, ], dashboardFilters, }); store.dispatch({ type: CHART_RENDERING_SUCCEEDED, key: sliceId }); const wrapper = setup(store); expect(wrapper.find('DetailsPanelPopover')).toExist(); expect( wrapper.find('[data-test="applied-filter-count"] .current'), ).toHaveText('1'); expect(wrapper.find('WarningFilled')).not.toExist(); }); }); describe('for native filters', () => { it("doesn't show number when there are no active filters", () => { const store = getMockStoreWithNativeFilters(); // start with basic dashboard state, dispatch an event to simulate query completion store.dispatch({ type: CHART_UPDATE_SUCCEEDED, key: sliceId, queriesResponse: [ { status: 'success', applied_filters: [], rejected_filters: [], }, ], }); store.dispatch({ type: CHART_RENDERING_SUCCEEDED, key: sliceId }); const wrapper = setup(store); expect(wrapper.find('[data-test="applied-filter-count"]')).not.toExist(); }); it('shows the indicator when filters have been applied', () => { // @ts-ignore global.featureFlags = { [SupersetUI.FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, }; const store = getMockStoreWithNativeFilters(); // start with basic dashboard state, dispatch an event to simulate query completion store.dispatch({ type: CHART_UPDATE_SUCCEEDED, key: sliceId, queriesResponse: [ { status: 'success', applied_filters: [{ column: 'region' }], rejected_filters: [], }, ], }); store.dispatch({ type: CHART_RENDERING_SUCCEEDED, key: sliceId }); const wrapper = setup(store); expect(wrapper.find('DetailsPanelPopover')).toExist(); expect( wrapper.find('[data-test="applied-filter-count"] .current'), ).toHaveText('1'); expect(wrapper.find('WarningFilled')).not.toExist(); }); }); });
7,144
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/FiltersBadge
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/FiltersBadge/DetailsPanel/DetailsPanel.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { Indicator } from 'src/dashboard/components/nativeFilters/selectors'; import DetailsPanel from '.'; const createProps = () => ({ appliedCrossFilterIndicators: [ { column: 'clinical_stage', name: 'Clinical Stage', value: [], status: 'UNSET', path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', ], }, ] as Indicator[], appliedIndicators: [ { column: 'country_name', name: 'Country', value: [], status: 'UNSET', path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', ], }, ] as Indicator[], incompatibleIndicators: [ { column: 'product_category_copy', name: 'Vaccine Approach Copy', value: [], status: 'UNSET', path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Zz', 'TAB-BCIJF4NvgQq', 'ROW-xSeNAspgww', 'CHART-eirDduqb1Aa', ], }, ] as Indicator[], unsetIndicators: [ { column: 'product_category', name: 'Vaccine Approach', value: [], status: 'UNSET', path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', ], }, ] as Indicator[], onHighlightFilterSource: jest.fn(), }); test('Should render "appliedCrossFilterIndicators"', async () => { const props = createProps(); props.appliedIndicators = []; props.incompatibleIndicators = []; props.unsetIndicators = []; render( <DetailsPanel {...props}> <div data-test="details-panel-content">Content</div> </DetailsPanel>, { useRedux: true }, ); userEvent.hover(screen.getByTestId('details-panel-content')); expect( await screen.findByText('Applied cross-filters (1)'), ).toBeInTheDocument(); expect( screen.getByRole('button', { name: 'Clinical Stage' }), ).toBeInTheDocument(); expect(props.onHighlightFilterSource).toBeCalledTimes(0); userEvent.click(screen.getByRole('button', { name: 'Clinical Stage' })); expect(props.onHighlightFilterSource).toBeCalledTimes(1); expect(props.onHighlightFilterSource).toBeCalledWith([ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', 'LABEL-clinical_stage', ]); }); test('Should render "appliedIndicators"', async () => { const props = createProps(); props.appliedCrossFilterIndicators = []; props.incompatibleIndicators = []; props.unsetIndicators = []; render( <DetailsPanel {...props}> <div data-test="details-panel-content">Content</div> </DetailsPanel>, { useRedux: true }, ); userEvent.hover(screen.getByTestId('details-panel-content')); expect(await screen.findByText('Applied filters (1)')).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Country' })).toBeInTheDocument(); expect(props.onHighlightFilterSource).toBeCalledTimes(0); userEvent.click(screen.getByRole('button', { name: 'Country' })); expect(props.onHighlightFilterSource).toBeCalledTimes(1); expect(props.onHighlightFilterSource).toBeCalledWith([ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', 'LABEL-country_name', ]); }); test('Should render empty', () => { const props = createProps(); props.appliedCrossFilterIndicators = []; props.appliedIndicators = []; props.incompatibleIndicators = []; props.unsetIndicators = []; render( <DetailsPanel {...props}> <div data-test="details-panel-content">Content</div> </DetailsPanel>, { useRedux: true }, ); expect(screen.getByTestId('details-panel-content')).toBeInTheDocument(); userEvent.click(screen.getByTestId('details-panel-content')); expect(screen.queryByRole('button')).not.toBeInTheDocument(); });
7,146
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/FiltersBadge
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/FiltersBadge/FilterIndicator/FilterIndicator.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { Indicator } from 'src/dashboard/components/nativeFilters/selectors'; import FilterIndicator from '.'; const createProps = () => ({ indicator: { column: 'product_category', name: 'Vaccine Approach', value: [] as any[], path: [ 'ROOT_ID', 'TABS-wUKya7eQ0Z', 'TAB-BCIJF4NvgQ', 'ROW-xSeNAspgw', 'CHART-eirDduqb1A', ], } as Indicator, onClick: jest.fn(), }); test('Should render', () => { const props = createProps(); render(<FilterIndicator {...props} />); expect( screen.getByRole('button', { name: 'Vaccine Approach' }), ).toBeInTheDocument(); expect(screen.getByRole('img')).toBeInTheDocument(); }); test('Should call "onClick"', () => { const props = createProps(); render(<FilterIndicator {...props} />); expect(props.onClick).toBeCalledTimes(0); userEvent.click(screen.getByRole('button', { name: 'Vaccine Approach' })); expect(props.onClick).toBeCalledTimes(1); }); test('Should render "value"', () => { const props = createProps(); props.indicator.value = ['any', 'string']; render(<FilterIndicator {...props} />); expect( screen.getByRole('button', { name: 'Vaccine Approach: any, string', }), ).toBeInTheDocument(); }); test('Should render with default props', () => { const props = createProps(); delete props.indicator.path; render(<FilterIndicator indicator={props.indicator} />); expect( screen.getByRole('button', { name: 'Vaccine Approach' }), ).toBeInTheDocument(); userEvent.click(screen.getByRole('button', { name: 'Vaccine Approach' })); });
7,148
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/Header/Header.test.tsx
/** * 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, fireEvent } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import fetchMock from 'fetch-mock'; import { getExtensionsRegistry } from '@superset-ui/core'; import setupExtensions from 'src/setup/setupExtensions'; import { HeaderProps } from './types'; import Header from '.'; const createProps = () => ({ addSuccessToast: jest.fn(), addDangerToast: jest.fn(), addWarningToast: jest.fn(), dashboardInfo: { id: 1, dash_edit_perm: false, dash_save_perm: false, dash_share_perm: false, userId: '1', metadata: {}, common: { conf: { DASHBOARD_AUTO_REFRESH_INTERVALS: [ [0, "Don't refresh"], [10, '10 seconds'], ], }, }, }, user: { createdOn: '2021-04-27T18:12:38.952304', email: '[email protected]', firstName: 'admin', isActive: true, lastName: 'admin', permissions: {}, roles: { Admin: [['menu_access', 'Manage']] }, userId: 1, username: 'admin', }, reports: {}, dashboardTitle: 'Dashboard Title', charts: {}, layout: {}, expandedSlices: {}, css: '', customCss: '', isStarred: false, isLoading: false, lastModifiedTime: 0, refreshFrequency: 0, shouldPersistRefreshFrequency: false, onSave: jest.fn(), onChange: jest.fn(), fetchFaveStar: jest.fn(), fetchCharts: jest.fn(), onRefresh: jest.fn(), saveFaveStar: jest.fn(), savePublished: jest.fn(), isPublished: false, updateDashboardTitle: jest.fn(), editMode: false, setEditMode: jest.fn(), showBuilderPane: jest.fn(), updateCss: jest.fn(), setColorScheme: jest.fn(), setUnsavedChanges: jest.fn(), logEvent: jest.fn(), setRefreshFrequency: jest.fn(), hasUnsavedChanges: false, maxUndoHistoryExceeded: false, onUndo: jest.fn(), onRedo: jest.fn(), undoLength: 0, redoLength: 0, setMaxUndoHistoryExceeded: jest.fn(), maxUndoHistoryToast: jest.fn(), dashboardInfoChanged: jest.fn(), dashboardTitleChanged: jest.fn(), showMenuDropdown: true, }); const props = createProps(); const editableProps = { ...props, editMode: true, dashboardInfo: { ...props.dashboardInfo, dash_edit_perm: true, dash_save_perm: true, }, }; const undoProps = { ...editableProps, undoLength: 1, }; const redoProps = { ...editableProps, redoLength: 1, }; fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {}); function setup(props: HeaderProps, initialState = {}) { return render( <div className="dashboard"> <Header {...props} /> </div>, { useRedux: true, initialState }, ); } async function openActionsDropdown() { const btn = screen.getByRole('img', { name: 'more-horiz' }); userEvent.click(btn); expect(await screen.findByTestId('header-actions-menu')).toBeInTheDocument(); } test('should render', () => { const mockedProps = createProps(); const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('should render the title', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByTestId('editable-title')).toHaveTextContent( 'Dashboard Title', ); }); test('should render the editable title', () => { setup(editableProps); expect(screen.getByDisplayValue('Dashboard Title')).toBeInTheDocument(); }); test('should edit the title', () => { setup(editableProps); const editableTitle = screen.getByDisplayValue('Dashboard Title'); expect(editableProps.onChange).not.toHaveBeenCalled(); userEvent.click(editableTitle); userEvent.clear(editableTitle); userEvent.type(editableTitle, 'New Title'); userEvent.click(document.body); expect(editableProps.onChange).toHaveBeenCalled(); expect(screen.getByDisplayValue('New Title')).toBeInTheDocument(); }); test('should render the "Draft" status', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByText('Draft')).toBeInTheDocument(); }); test('should publish', () => { const mockedProps = createProps(); const canEditProps = { ...mockedProps, dashboardInfo: { ...mockedProps.dashboardInfo, dash_edit_perm: true, dash_save_perm: true, }, }; setup(canEditProps); const draft = screen.getByText('Draft'); expect(mockedProps.savePublished).toHaveBeenCalledTimes(0); userEvent.click(draft); expect(mockedProps.savePublished).toHaveBeenCalledTimes(1); }); test('should render the "Undo" action as disabled', () => { setup(editableProps); expect(screen.getByTestId('undo-action').parentElement).toBeDisabled(); }); test('should undo', () => { setup(undoProps); const undo = screen.getByTestId('undo-action'); expect(undoProps.onUndo).not.toHaveBeenCalled(); userEvent.click(undo); expect(undoProps.onUndo).toHaveBeenCalledTimes(1); }); test('should undo with key listener', () => { undoProps.onUndo.mockReset(); setup(undoProps); expect(undoProps.onUndo).not.toHaveBeenCalled(); fireEvent.keyDown(document.body, { key: 'z', code: 'KeyZ', ctrlKey: true }); expect(undoProps.onUndo).toHaveBeenCalledTimes(1); }); test('should render the "Redo" action as disabled', () => { setup(editableProps); expect(screen.getByTestId('redo-action').parentElement).toBeDisabled(); }); test('should redo', () => { setup(redoProps); const redo = screen.getByTestId('redo-action'); expect(redoProps.onRedo).not.toHaveBeenCalled(); userEvent.click(redo); expect(redoProps.onRedo).toHaveBeenCalledTimes(1); }); test('should redo with key listener', () => { redoProps.onRedo.mockReset(); setup(redoProps); expect(redoProps.onRedo).not.toHaveBeenCalled(); fireEvent.keyDown(document.body, { key: 'y', code: 'KeyY', ctrlKey: true }); expect(redoProps.onRedo).toHaveBeenCalledTimes(1); }); test('should render the "Discard changes" button', () => { setup(editableProps); expect(screen.getByText('Discard')).toBeInTheDocument(); }); test('should render the "Save" button as disabled', () => { setup(editableProps); expect(screen.getByText('Save').parentElement).toBeDisabled(); }); test('should save', () => { const unsavedProps = { ...editableProps, hasUnsavedChanges: true, }; setup(unsavedProps); const save = screen.getByText('Save'); expect(unsavedProps.onSave).not.toHaveBeenCalled(); userEvent.click(save); expect(unsavedProps.onSave).toHaveBeenCalledTimes(1); }); test('should NOT render the "Draft" status', () => { const mockedProps = createProps(); const publishedProps = { ...mockedProps, isPublished: true, }; setup(publishedProps); expect(screen.queryByText('Draft')).not.toBeInTheDocument(); }); test('should render the unselected fave icon', () => { const mockedProps = createProps(); setup(mockedProps); expect(mockedProps.fetchFaveStar).toHaveBeenCalled(); expect( screen.getByRole('img', { name: 'favorite-unselected' }), ).toBeInTheDocument(); }); test('should render the selected fave icon', () => { const mockedProps = createProps(); const favedProps = { ...mockedProps, isStarred: true, }; setup(favedProps); expect( screen.getByRole('img', { name: 'favorite-selected' }), ).toBeInTheDocument(); }); test('should NOT render the fave icon on anonymous user', () => { const mockedProps = createProps(); const anonymousUserProps = { ...mockedProps, user: undefined, }; setup(anonymousUserProps); expect(() => screen.getByRole('img', { name: 'favorite-unselected' }), ).toThrowError('Unable to find'); expect(() => screen.getByRole('img', { name: 'favorite-selected' }), ).toThrowError('Unable to find'); }); test('should fave', async () => { const mockedProps = createProps(); setup(mockedProps); const fave = screen.getByRole('img', { name: 'favorite-unselected' }); expect(mockedProps.saveFaveStar).not.toHaveBeenCalled(); userEvent.click(fave); expect(mockedProps.saveFaveStar).toHaveBeenCalledTimes(1); }); test('should toggle the edit mode', () => { const mockedProps = createProps(); const canEditProps = { ...mockedProps, dashboardInfo: { ...mockedProps.dashboardInfo, dash_edit_perm: true, }, }; setup(canEditProps); const editDashboard = screen.getByText('Edit dashboard'); expect(screen.queryByText('Edit dashboard')).toBeInTheDocument(); userEvent.click(editDashboard); expect(mockedProps.logEvent).toHaveBeenCalled(); }); test('should render the dropdown icon', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByRole('img', { name: 'more-horiz' })).toBeInTheDocument(); }); test('should refresh the charts', async () => { const mockedProps = createProps(); setup(mockedProps); await openActionsDropdown(); userEvent.click(screen.getByText('Refresh dashboard')); expect(mockedProps.onRefresh).toHaveBeenCalledTimes(1); }); test('should render an extension component if one is supplied', () => { const extensionsRegistry = getExtensionsRegistry(); extensionsRegistry.set('dashboard.nav.right', () => ( <>dashboard.nav.right extension component</> )); setupExtensions(); const mockedProps = createProps(); setup(mockedProps); expect( screen.getByText('dashboard.nav.right extension component'), ).toBeInTheDocument(); });
7,151
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/Header
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/Header/HeaderActionsDropdown/HeaderActionsDropdown.test.tsx
/** * 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 { shallow } from 'enzyme'; import sinon from 'sinon'; import { render, screen } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import fetchMock from 'fetch-mock'; import { HeaderDropdownProps } from 'src/dashboard/components/Header/types'; import injectCustomCss from 'src/dashboard/util/injectCustomCss'; import { FeatureFlag } from '@superset-ui/core'; import * as uiCore from '@superset-ui/core'; import HeaderActionsDropdown from '.'; let isFeatureEnabledMock: jest.MockInstance<boolean, [feature: FeatureFlag]>; const createProps = () => ({ addSuccessToast: jest.fn(), addDangerToast: jest.fn(), customCss: '.ant-menu {margin-left: 100px;}', dashboardId: 1, dashboardInfo: { id: 1, dash_edit_perm: true, dash_save_perm: true, userId: '1', metadata: {}, common: { conf: { DASHBOARD_AUTO_REFRESH_INTERVALS: [ [0, "Don't refresh"], [10, '10 seconds'], ], }, }, }, dashboardTitle: 'Title', editMode: false, expandedSlices: {}, forceRefreshAllCharts: jest.fn(), hasUnsavedChanges: false, isLoading: false, layout: {}, onChange: jest.fn(), onSave: jest.fn(), refreshFrequency: 200, setRefreshFrequency: jest.fn(), shouldPersistRefreshFrequency: false, showPropertiesModal: jest.fn(), startPeriodicRender: jest.fn(), updateCss: jest.fn(), userCanEdit: false, userCanSave: false, userCanShare: false, userCanCurate: false, lastModifiedTime: 0, isDropdownVisible: true, dataMask: {}, logEvent: jest.fn(), }); const editModeOnProps = { ...createProps(), editMode: true, }; const editModeOnWithFilterScopesProps = { ...editModeOnProps, dashboardInfo: { ...editModeOnProps.dashboardInfo, metadata: { filter_scopes: { '1': { scopes: ['ROOT_ID'], immune: [] }, }, }, }, }; function setup(props: HeaderDropdownProps) { return render( <div className="dashboard-header"> <HeaderActionsDropdown {...props} /> </div>, { useRedux: true }, ); } fetchMock.get('glob:*/csstemplateasyncmodelview/api/read', {}); test('should render', () => { const mockedProps = createProps(); const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('should render the Download dropdown button when not in edit mode', () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByRole('button', { name: 'Download' })).toBeInTheDocument(); }); test('should render the menu items', async () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getAllByRole('menuitem')).toHaveLength(4); expect(screen.getByText('Refresh dashboard')).toBeInTheDocument(); expect(screen.getByText('Set auto-refresh interval')).toBeInTheDocument(); expect(screen.getByText('Enter fullscreen')).toBeInTheDocument(); expect(screen.getByText('Download')).toBeInTheDocument(); }); test('should render the menu items in edit mode', async () => { setup(editModeOnProps); expect(screen.getAllByRole('menuitem')).toHaveLength(5); expect(screen.getByText('Set auto-refresh interval')).toBeInTheDocument(); expect(screen.getByText('Edit properties')).toBeInTheDocument(); expect(screen.getByText('Edit CSS')).toBeInTheDocument(); expect(screen.getByText('Download')).toBeInTheDocument(); }); describe('with native filters feature flag disabled', () => { beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation( (featureFlag: FeatureFlag) => featureFlag !== FeatureFlag.DASHBOARD_NATIVE_FILTERS, ); }); afterAll(() => { // @ts-ignore isFeatureEnabledMock.restore(); }); it('should render filter mapping in edit mode if explicit filter scopes undefined', async () => { setup(editModeOnProps); expect(screen.getByText('Set filter mapping')).toBeInTheDocument(); }); it('should render filter mapping in edit mode if explicit filter scopes defined', async () => { setup(editModeOnWithFilterScopesProps); expect(screen.getByText('Set filter mapping')).toBeInTheDocument(); }); }); describe('with native filters feature flag enabled', () => { beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation( (featureFlag: FeatureFlag) => featureFlag === FeatureFlag.DASHBOARD_NATIVE_FILTERS, ); }); afterAll(() => { // @ts-ignore isFeatureEnabledMock.restore(); }); it('should not render filter mapping in edit mode if explicit filter scopes undefined', async () => { setup(editModeOnProps); expect(screen.queryByText('Set filter mapping')).not.toBeInTheDocument(); }); it('should render filter mapping in edit mode if explicit filter scopes defined', async () => { setup(editModeOnWithFilterScopesProps); expect(screen.getByText('Set filter mapping')).toBeInTheDocument(); }); }); test('should show the share actions', async () => { const mockedProps = createProps(); const canShareProps = { ...mockedProps, userCanShare: true, }; setup(canShareProps); expect(screen.getByText('Share')).toBeInTheDocument(); }); test('should render the "Save as" menu item when user can save', async () => { const mockedProps = createProps(); const canSaveProps = { ...mockedProps, userCanSave: true, }; setup(canSaveProps); expect(screen.getByText('Save as')).toBeInTheDocument(); }); test('should NOT render the "Save as" menu item when user cannot save', async () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.queryByText('Save as')).not.toBeInTheDocument(); }); test('should render the "Refresh dashboard" menu item as disabled when loading', async () => { const mockedProps = createProps(); const loadingProps = { ...mockedProps, isLoading: true, }; setup(loadingProps); expect(screen.getByText('Refresh dashboard')).toHaveClass( 'ant-menu-item-disabled', ); }); test('should NOT render the "Refresh dashboard" menu item as disabled', async () => { const mockedProps = createProps(); setup(mockedProps); expect(screen.getByText('Refresh dashboard')).not.toHaveClass( 'ant-menu-item-disabled', ); }); test('should render with custom css', () => { const mockedProps = createProps(); const { customCss } = mockedProps; setup(mockedProps); injectCustomCss(customCss); expect(screen.getByTestId('header-actions-menu')).toHaveStyle( 'margin-left: 100px', ); }); test('should refresh the charts', async () => { const mockedProps = createProps(); setup(mockedProps); userEvent.click(screen.getByText('Refresh dashboard')); expect(mockedProps.forceRefreshAllCharts).toHaveBeenCalledTimes(1); expect(mockedProps.addSuccessToast).toHaveBeenCalledTimes(1); }); test('should show the properties modal', async () => { setup(editModeOnProps); userEvent.click(screen.getByText('Edit properties')); expect(editModeOnProps.showPropertiesModal).toHaveBeenCalledTimes(1); }); describe('UNSAFE_componentWillReceiveProps', () => { let wrapper: any; const mockedProps = createProps(); const props = { ...mockedProps, customCss: '' }; beforeEach(() => { wrapper = shallow(<HeaderActionsDropdown {...props} />); wrapper.setState({ css: props.customCss }); sinon.spy(wrapper.instance(), 'setState'); }); afterEach(() => { wrapper.instance().setState.restore(); }); it('css should update state and inject custom css', () => { wrapper.instance().UNSAFE_componentWillReceiveProps({ ...props, customCss: mockedProps.customCss, }); expect(wrapper.instance().setState.calledOnce).toBe(true); const stateKeys = Object.keys(wrapper.instance().setState.lastCall.args[0]); expect(stateKeys).toContain('css'); }); });
7,153
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/OverwriteConfirm/OverwriteConfirm.test.tsx
/** * 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 configureStore from 'redux-mock-store'; import { render, waitFor } from 'spec/helpers/testing-library'; import { overwriteConfirmMetadata } from 'spec/fixtures/mockDashboardState'; import OverwriteConfirm from '.'; import './OverwriteConfirmModal'; const mockStore = configureStore(); test('renders nothing without overwriteConfirmMetadata', () => { const { queryByText } = render(<OverwriteConfirm />, { useRedux: true, store: mockStore({ dashboardState: {} }), }); expect(queryByText('Confirm overwrite')).not.toBeInTheDocument(); }); test('renders confirm modal on overwriteConfirmMetadata is provided', async () => { const { queryByText } = render(<OverwriteConfirm />, { useRedux: true, store: mockStore({ dashboardState: { overwriteConfirmMetadata, }, }), }); await waitFor(() => expect(queryByText('Confirm overwrite')).toBeInTheDocument(), ); });
7,154
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/OverwriteConfirm/OverwriteConfirmModal.test.tsx
/** * 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 thunk from 'redux-thunk'; import configureStore from 'redux-mock-store'; import fetchMock from 'fetch-mock'; import { mockAllIsIntersecting } from 'react-intersection-observer/test-utils'; import { fireEvent, render, waitFor } from 'spec/helpers/testing-library'; import { overwriteConfirmMetadata } from 'spec/fixtures/mockDashboardState'; import OverwriteConfirmModal from './OverwriteConfirmModal'; const middlewares = [thunk]; const mockStore = configureStore(middlewares); jest.mock('react-diff-viewer-continued', () => () => ( <div data-test="mock-diff-viewer" /> )); test('renders diff viewer when it contains overwriteConfirmMetadata', async () => { const { queryByText, findAllByTestId } = render( <OverwriteConfirmModal overwriteConfirmMetadata={overwriteConfirmMetadata} />, { useRedux: true, store: mockStore(), }, ); expect(queryByText('Confirm overwrite')).toBeInTheDocument(); const diffViewers = await findAllByTestId('mock-diff-viewer'); expect(diffViewers).toHaveLength( overwriteConfirmMetadata.overwriteConfirmItems.length, ); }); test('requests update dashboard api when save button is clicked', async () => { const updateDashboardEndpoint = `glob:*/api/v1/dashboard/${overwriteConfirmMetadata.dashboardId}`; fetchMock.put(updateDashboardEndpoint, { id: overwriteConfirmMetadata.dashboardId, last_modified_time: +new Date(), result: overwriteConfirmMetadata.data, }); const store = mockStore({ dashboardLayout: {}, dashboardFilters: {}, }); const { findByTestId } = render( <OverwriteConfirmModal overwriteConfirmMetadata={overwriteConfirmMetadata} />, { useRedux: true, store, }, ); const saveButton = await findByTestId('overwrite-confirm-save-button'); expect(fetchMock.calls(updateDashboardEndpoint)).toHaveLength(0); fireEvent.click(saveButton); expect(fetchMock.calls(updateDashboardEndpoint)).toHaveLength(0); mockAllIsIntersecting(true); fireEvent.click(saveButton); await waitFor(() => expect(fetchMock.calls(updateDashboardEndpoint)?.[0]?.[1]?.body).toEqual( JSON.stringify(overwriteConfirmMetadata.data), ), ); await waitFor(() => expect(store.getActions()).toContainEqual({ type: 'SET_OVERRIDE_CONFIRM', overwriteConfirmMetadata: undefined, }), ); });
7,158
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/PropertiesModal/PropertiesModal.test.tsx
/** * 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 fetchMock from 'fetch-mock'; import userEvent from '@testing-library/user-event'; import * as ColorSchemeControlWrapper from 'src/dashboard/components/ColorSchemeControlWrapper'; import * as SupersetCore from '@superset-ui/core'; import PropertiesModal from '.'; const spyIsFeatureEnabled = jest.spyOn(SupersetCore, 'isFeatureEnabled'); const spyColorSchemeControlWrapper = jest.spyOn( ColorSchemeControlWrapper, 'default', ); const mockedJsonMetadata = '{"timed_refresh_immune_slices": [], "expanded_slices": {}, "refresh_frequency": 0, "default_filters": "{}", "color_scheme": "supersetColors", "label_colors": {"0": "#D3B3DA", "1": "#9EE5E5", "0. Pre-clinical": "#1FA8C9", "2. Phase II or Combined I/II": "#454E7C", "1. Phase I": "#5AC189", "3. Phase III": "#FF7F44", "4. Authorized": "#666666", "root": "#1FA8C9", "Protein subunit": "#454E7C", "Phase II": "#5AC189", "Pre-clinical": "#FF7F44", "Phase III": "#666666", "Phase I": "#E04355", "Phase I/II": "#FCC700", "Inactivated virus": "#A868B7", "Virus-like particle": "#3CCCCB", "Replicating bacterial vector": "#A38F79", "DNA-based": "#8FD3E4", "RNA-based vaccine": "#A1A6BD", "Authorized": "#ACE1C4", "Non-replicating viral vector": "#FEC0A1", "Replicating viral vector": "#B2B2B2", "Unknown": "#EFA1AA", "Live attenuated virus": "#FDE380", "COUNT(*)": "#D1C6BC"}, "filter_scopes": {"358": {"Country_Name": {"scope": ["ROOT_ID"], "immune": []}, "Product_Category": {"scope": ["ROOT_ID"], "immune": []}, "Clinical Stage": {"scope": ["ROOT_ID"], "immune": []}}}}'; spyColorSchemeControlWrapper.mockImplementation( () => (<div>ColorSchemeControlWrapper</div>) as any, ); fetchMock.get( 'http://localhost/api/v1/dashboard/related/roles?q=(filter:%27%27,page:0,page_size:100)', { body: { count: 6, result: [ { text: 'Admin', value: 1, extra: {}, }, { text: 'Alpha', value: 3, extra: {}, }, { text: 'Gamma', value: 4, extra: {}, }, { text: 'Public', value: 2, extra: {}, }, { text: 'sql_lab', value: 6, extra: {}, }, ], }, }, ); fetchMock.get( 'http://localhost/api/v1/dashboard/related/owners?q=(filter:%27%27,page:0,page_size:100)', { body: { count: 1, result: [ { text: 'Superset Admin', value: 1, extra: { active: true }, }, { text: 'Inactive Admin', value: 2, extra: { active: false }, }, ], }, }, ); const dashboardInfo = { certified_by: 'John Doe', certification_details: 'Sample certification', changed_by: null, changed_by_name: '', changed_on: '2021-03-30T19:30:14.020942', charts: [ 'Vaccine Candidates per Country & Stage', 'Vaccine Candidates per Country', 'Vaccine Candidates per Country', 'Vaccine Candidates per Approach & Stage', 'Vaccine Candidates per Phase', 'Vaccine Candidates per Phase', 'Vaccine Candidates per Country & Stage', 'Filtering Vaccines', ], css: '', dashboard_title: 'COVID Vaccine Dashboard', id: 26, metadata: mockedJsonMetadata, owners: [], position_json: '{"CHART-63bEuxjDMJ": {"children": [], "id": "CHART-63bEuxjDMJ", "meta": {"chartId": 369, "height": 76, "sliceName": "Vaccine Candidates per Country", "sliceNameOverride": "Map of Vaccine Candidates", "uuid": "ddc91df6-fb40-4826-bdca-16b85af1c024", "width": 7}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-zvw7luvEL"], "type": "CHART"}, "CHART-F-fkth0Dnv": {"children": [], "id": "CHART-F-fkth0Dnv", "meta": {"chartId": 314, "height": 76, "sliceName": "Vaccine Candidates per Country", "sliceNameOverride": "Treemap of Vaccine Candidates per Country", "uuid": "e2f5a8a7-feb0-4f79-bc6b-01fe55b98b3c", "width": 5}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-zvw7luvEL"], "type": "CHART"}, "CHART-RjD_ygqtwH": {"children": [], "id": "CHART-RjD_ygqtwH", "meta": {"chartId": 351, "height": 59, "sliceName": "Vaccine Candidates per Phase", "sliceNameOverride": "Vaccine Candidates per Phase", "uuid": "30b73c65-85e7-455f-bb24-801bb0cdc670", "width": 2}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-xSeNAspgw"], "type": "CHART"}, "CHART-aGfmWtliqA": {"children": [], "id": "CHART-aGfmWtliqA", "meta": {"chartId": 312, "height": 59, "sliceName": "Vaccine Candidates per Phase", "uuid": "392f293e-0892-4316-bd41-c927b65606a4", "width": 4}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-xSeNAspgw"], "type": "CHART"}, "CHART-dCUpAcPsji": {"children": [], "id": "CHART-dCUpAcPsji", "meta": {"chartId": 325, "height": 82, "sliceName": "Vaccine Candidates per Country & Stage", "sliceNameOverride": "Heatmap of Countries & Clinical Stages", "uuid": "cd111331-d286-4258-9020-c7949a109ed2", "width": 4}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-zhOlQLQnB"], "type": "CHART"}, "CHART-eirDduqb1A": {"children": [], "id": "CHART-eirDduqb1A", "meta": {"chartId": 358, "height": 59, "sliceName": "Filtering Vaccines", "sliceNameOverride": "Filter Box of Vaccines", "uuid": "c29381ce-0e99-4cf3-bf0f-5f55d6b94176", "width": 3}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-xSeNAspgw"], "type": "CHART"}, "CHART-fYo7IyvKZQ": {"children": [], "id": "CHART-fYo7IyvKZQ", "meta": {"chartId": 371, "height": 82, "sliceName": "Vaccine Candidates per Country & Stage", "sliceNameOverride": "Sunburst of Country & Clinical Stages", "uuid": "f69c556f-15fe-4a82-a8bb-69d5b6954123", "width": 5}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-zhOlQLQnB"], "type": "CHART"}, "CHART-j4hUvP5dDD": {"children": [], "id": "CHART-j4hUvP5dDD", "meta": {"chartId": 364, "height": 82, "sliceName": "Vaccine Candidates per Approach & Stage", "sliceNameOverride": "Heatmap of Approaches & Clinical Stages", "uuid": "0c953c84-0c9a-418d-be9f-2894d2a2cee0", "width": 3}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-zhOlQLQnB"], "type": "CHART"}, "DASHBOARD_VERSION_KEY": "v2", "GRID_ID": {"children": [], "id": "GRID_ID", "parents": ["ROOT_ID"], "type": "GRID"}, "HEADER_ID": {"id": "HEADER_ID", "meta": {"text": "COVID Vaccine Dashboard"}, "type": "HEADER"}, "MARKDOWN-VjQQ5SFj5v": {"children": [], "id": "MARKDOWN-VjQQ5SFj5v", "meta": {"code": "# COVID-19 Vaccine Dashboard\\n\\nEverywhere you look, you see negative news about COVID-19. This is to be expected; it\'s been a brutal year and this disease is no joke. This dashboard hopes to use visualization to inject some optimism about the coming return to normalcy we enjoyed before 2020! There\'s lots to be optimistic about:\\n\\n- the sheer volume of attempts to fund the R&D needed to produce and bring an effective vaccine to market\\n- the large number of countries involved in at least one vaccine candidate (and the diversity of economic status of these countries)\\n- the diversity of vaccine approaches taken\\n- the fact that 2 vaccines have already been approved (and a hundreds of thousands of patients have already been vaccinated)\\n\\n### The Dataset\\n\\nThis dashboard is powered by data maintained by the Millken Institute ([link to dataset](https://airtable.com/shrSAi6t5WFwqo3GM/tblEzPQS5fnc0FHYR/viwDBH7b6FjmIBX5x?blocks=bipZFzhJ7wHPv7x9z)). We researched each vaccine candidate and added our own best guesses for the country responsible for each vaccine effort.\\n\\n_Note that this dataset was last updated on 12/23/2020_.\\n\\n", "height": 59, "width": 3}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ", "ROW-xSeNAspgw"], "type": "MARKDOWN"}, "ROOT_ID": {"children": ["TABS-wUKya7eQ0Z"], "id": "ROOT_ID", "type": "ROOT"}, "ROW-xSeNAspgw": {"children": ["MARKDOWN-VjQQ5SFj5v", "CHART-aGfmWtliqA", "CHART-RjD_ygqtwH", "CHART-eirDduqb1A"], "id": "ROW-xSeNAspgw", "meta": {"0": "ROOT_ID", "background": "BACKGROUND_TRANSPARENT"}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ"], "type": "ROW"}, "ROW-zhOlQLQnB": {"children": ["CHART-j4hUvP5dDD", "CHART-dCUpAcPsji", "CHART-fYo7IyvKZQ"], "id": "ROW-zhOlQLQnB", "meta": {"0": "ROOT_ID", "background": "BACKGROUND_TRANSPARENT"}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ"], "type": "ROW"}, "ROW-zvw7luvEL": {"children": ["CHART-63bEuxjDMJ", "CHART-F-fkth0Dnv"], "id": "ROW-zvw7luvEL", "meta": {"0": "ROOT_ID", "background": "BACKGROUND_TRANSPARENT"}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z", "TAB-BCIJF4NvgQ"], "type": "ROW"}, "TAB-BCIJF4NvgQ": {"children": ["ROW-xSeNAspgw", "ROW-zvw7luvEL", "ROW-zhOlQLQnB"], "id": "TAB-BCIJF4NvgQ", "meta": {"text": "Overview"}, "parents": ["ROOT_ID", "TABS-wUKya7eQ0Z"], "type": "TAB"}, "TABS-wUKya7eQ0Z": {"children": ["TAB-BCIJF4NvgQ"], "id": "TABS-wUKya7eQ0Z", "meta": {}, "parents": ["ROOT_ID"], "type": "TABS"}}', published: false, roles: [], slug: null, thumbnail_url: '/api/v1/dashboard/26/thumbnail/b24805e98d90116da8c0974d24f5c533/', url: '/superset/dashboard/26/', }; fetchMock.get('glob:*/api/v1/dashboard/26', { body: { result: { ...dashboardInfo, json_metadata: mockedJsonMetadata }, }, }); const createProps = () => ({ certified_by: 'John Doe', certification_details: 'Sample certification', dashboardId: 26, show: true, colorScheme: 'supersetColors', onlyApply: false, onHide: jest.fn(), onSubmit: jest.fn(), addSuccessToast: jest.fn(), }); beforeEach(() => { jest.clearAllMocks(); }); afterAll(() => { fetchMock.restore(); }); test('should render - FeatureFlag disabled', async () => { spyIsFeatureEnabled.mockReturnValue(false); const props = createProps(); render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect(screen.getByRole('dialog')).toBeInTheDocument(); expect( screen.getByRole('heading', { name: 'Basic information' }), ).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Access' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Colors' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Advanced' })).toBeInTheDocument(); expect( screen.getByRole('heading', { name: 'Certification' }), ).toBeInTheDocument(); expect(screen.getAllByRole('heading')).toHaveLength(5); expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Advanced' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(4); expect(screen.getAllByRole('textbox')).toHaveLength(4); expect(screen.getByRole('combobox')).toBeInTheDocument(); expect(spyColorSchemeControlWrapper).toBeCalledWith( expect.objectContaining({ colorScheme: 'supersetColors' }), {}, ); }); test('should render - FeatureFlag enabled', async () => { spyIsFeatureEnabled.mockReturnValue(true); const props = createProps(); render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect( screen.getByRole('dialog', { name: 'Dashboard properties' }), ).toBeInTheDocument(); expect( screen.getByRole('heading', { name: 'Basic information' }), ).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Access' })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Advanced' })).toBeInTheDocument(); expect( screen.getByRole('heading', { name: 'Certification' }), ).toBeInTheDocument(); // Tags will be included since isFeatureFlag always returns true in this test expect(screen.getByRole('heading', { name: 'Tags' })).toBeInTheDocument(); expect(screen.getAllByRole('heading')).toHaveLength(5); expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Advanced' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument(); expect(screen.getAllByRole('button')).toHaveLength(4); expect(screen.getAllByRole('textbox')).toHaveLength(4); expect(screen.getAllByRole('combobox')).toHaveLength(3); expect(spyColorSchemeControlWrapper).toBeCalledWith( expect.objectContaining({ colorScheme: 'supersetColors' }), {}, ); }); test('should open advance', async () => { spyIsFeatureEnabled.mockReturnValue(true); const props = createProps(); render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect(screen.getAllByRole('textbox')).toHaveLength(4); expect(screen.getAllByRole('combobox')).toHaveLength(3); userEvent.click(screen.getByRole('button', { name: 'Advanced' })); expect(screen.getAllByRole('textbox')).toHaveLength(5); expect(screen.getAllByRole('combobox')).toHaveLength(3); }); test('should close modal', async () => { spyIsFeatureEnabled.mockReturnValue(true); const props = createProps(); render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect(props.onHide).not.toBeCalled(); userEvent.click(screen.getByRole('button', { name: 'Cancel' })); expect(props.onHide).toBeCalledTimes(1); userEvent.click(screen.getByRole('button', { name: 'Close' })); expect(props.onHide).toBeCalledTimes(2); }); test('submitting with onlyApply:false', async () => { const put = jest.spyOn(SupersetCore.SupersetClient, 'put'); const spyGetCategoricalSchemeRegistry = jest.spyOn( SupersetCore, 'getCategoricalSchemeRegistry', ); spyGetCategoricalSchemeRegistry.mockReturnValue({ keys: () => ['supersetColors'], get: () => ['#FFFFFF', '#000000'], } as any); put.mockResolvedValue({ json: { result: { roles: 'roles', dashboard_title: 'dashboard_title', slug: 'slug', json_metadata: 'json_metadata', owners: 'owners', }, }, } as any); spyIsFeatureEnabled.mockReturnValue(false); const props = createProps(); props.onlyApply = false; render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect(props.onHide).not.toBeCalled(); expect(props.onSubmit).not.toBeCalled(); userEvent.click(screen.getByRole('button', { name: 'Save' })); await waitFor(() => { expect(props.onSubmit).toBeCalledTimes(1); expect(props.onSubmit).toBeCalledWith({ certificationDetails: 'Sample certification', certifiedBy: 'John Doe', colorScheme: 'supersetColors', colorNamespace: undefined, id: 26, jsonMetadata: expect.anything(), owners: [], slug: '', title: 'COVID Vaccine Dashboard', }); }); }); test('submitting with onlyApply:true', async () => { const spyGetCategoricalSchemeRegistry = jest.spyOn( SupersetCore, 'getCategoricalSchemeRegistry', ); spyGetCategoricalSchemeRegistry.mockReturnValue({ keys: () => ['supersetColors'], get: () => ['#FFFFFF', '#000000'], } as any); spyIsFeatureEnabled.mockReturnValue(false); const props = createProps(); props.onlyApply = true; render(<PropertiesModal {...props} />, { useRedux: true, }); expect( await screen.findByTestId('dashboard-edit-properties-form'), ).toBeInTheDocument(); expect(props.onHide).not.toBeCalled(); expect(props.onSubmit).not.toBeCalled(); userEvent.click(screen.getByRole('button', { name: 'Apply' })); await waitFor(() => { expect(props.onSubmit).toBeCalledTimes(1); }); }); test('Empty "Certified by" should clear "Certification details"', async () => { const props = createProps(); const noCertifiedByProps = { ...props, certified_by: '', }; render(<PropertiesModal {...noCertifiedByProps} />, { useRedux: true, }); expect( screen.getByRole('textbox', { name: 'Certification details' }), ).toHaveValue(''); }); test('should show all roles', async () => { spyIsFeatureEnabled.mockReturnValue(true); const props = createProps(); const propsWithDashboardIndo = { ...props, dashboardInfo }; const open = () => waitFor(() => userEvent.click(getSelect())); const getSelect = () => screen.getByRole('combobox', { name: SupersetCore.t('Roles') }); const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const findAllSelectOptions = () => waitFor(() => getElementsByClassName('.ant-select-item-option-content')); render(<PropertiesModal {...propsWithDashboardIndo} />, { useRedux: true, }); expect(screen.getAllByRole('combobox')).toHaveLength(3); expect( screen.getByRole('combobox', { name: SupersetCore.t('Roles') }), ).toBeInTheDocument(); await open(); const options = await findAllSelectOptions(); expect(options).toHaveLength(5); expect(options[0]).toHaveTextContent('Admin'); }); test('should show active owners with dashboard rbac', async () => { spyIsFeatureEnabled.mockReturnValue(true); const props = createProps(); const propsWithDashboardIndo = { ...props, dashboardInfo }; const open = () => waitFor(() => userEvent.click(getSelect())); const getSelect = () => screen.getByRole('combobox', { name: SupersetCore.t('Owners') }); const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const findAllSelectOptions = () => waitFor(() => getElementsByClassName('.ant-select-item-option-content')); render(<PropertiesModal {...propsWithDashboardIndo} />, { useRedux: true, }); expect(screen.getAllByRole('combobox')).toHaveLength(3); expect( screen.getByRole('combobox', { name: SupersetCore.t('Owners') }), ).toBeInTheDocument(); await open(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); expect(options[0]).toHaveTextContent('Superset Admin'); }); test('should show active owners without dashboard rbac', async () => { spyIsFeatureEnabled.mockReturnValue(false); const props = createProps(); const propsWithDashboardIndo = { ...props, dashboardInfo }; const open = () => waitFor(() => userEvent.click(getSelect())); const getSelect = () => screen.getByRole('combobox', { name: SupersetCore.t('Owners') }); const getElementsByClassName = (className: string) => document.querySelectorAll(className)! as NodeListOf<HTMLElement>; const findAllSelectOptions = () => waitFor(() => getElementsByClassName('.ant-select-item-option-content')); render(<PropertiesModal {...propsWithDashboardIndo} />, { useRedux: true, }); expect(screen.getByRole('combobox')).toBeInTheDocument(); expect( screen.getByRole('combobox', { name: SupersetCore.t('Owners') }), ).toBeInTheDocument(); await open(); const options = await findAllSelectOptions(); expect(options).toHaveLength(1); expect(options[0]).toHaveTextContent('Superset Admin'); });
7,160
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/PublishedStatus/PublishedStatus.test.tsx
/** * 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 PublishedStatus from '.'; const defaultProps = { dashboardId: 1, isPublished: false, savePublished: jest.fn(), canEdit: false, canSave: false, }; test('renders with unpublished status and readonly permissions', async () => { const tooltip = /This dashboard is not published which means it will not show up in the list of dashboards/; render(<PublishedStatus {...defaultProps} />); expect(screen.getByText('Draft')).toBeInTheDocument(); userEvent.hover(screen.getByText('Draft')); expect(await screen.findByText(tooltip)).toBeInTheDocument(); }); test('renders with unpublished status and write permissions', async () => { const tooltip = /This dashboard is not published, it will not show up in the list of dashboards/; const savePublished = jest.fn(); render( <PublishedStatus {...defaultProps} canEdit canSave savePublished={savePublished} />, ); expect(screen.getByText('Draft')).toBeInTheDocument(); userEvent.hover(screen.getByText('Draft')); expect(await screen.findByText(tooltip)).toBeInTheDocument(); expect(savePublished).not.toHaveBeenCalled(); userEvent.click(screen.getByText('Draft')); expect(savePublished).toHaveBeenCalledTimes(1); }); test('renders with published status and readonly permissions', () => { render(<PublishedStatus {...defaultProps} isPublished />); expect(screen.queryByText('Published')).not.toBeInTheDocument(); }); test('renders with published status and write permissions', async () => { const tooltip = /This dashboard is published. Click to make it a draft/; const savePublished = jest.fn(); render( <PublishedStatus {...defaultProps} isPublished canEdit canSave savePublished={savePublished} />, ); expect(screen.getByText('Published')).toBeInTheDocument(); userEvent.hover(screen.getByText('Published')); expect(await screen.findByText(tooltip)).toBeInTheDocument(); expect(savePublished).not.toHaveBeenCalled(); userEvent.click(screen.getByText('Published')); expect(savePublished).toHaveBeenCalledTimes(1); });
7,162
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/SliceHeader/SliceHeader.test.tsx
/** * 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 { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import { getExtensionsRegistry } from '@superset-ui/core'; import { render, screen } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import SliceHeader from '.'; jest.mock('src/dashboard/components/SliceHeaderControls', () => ({ __esModule: true, default: (props: any) => ( <div data-test="SliceHeaderControls" data-slice={JSON.stringify(props.slice)} data-is-cached={props.isCached} data-is-expanded={props.isExpanded} data-cached-dttm={props.cachedDttm} data-updated-dttm={props.updatedDttm} data-superset-can-explore={props.supersetCanExplore} data-superset-can-csv={props.supersetCanCSV} data-component-id={props.componentId} data-dashboard-id={props.dashboardId} data-is-full-size={props.isFullSize} data-chart-status={props.chartStatus} > <button type="button" data-test="toggleExpandSlice" onClick={props.toggleExpandSlice} > toggleExpandSlice </button> <button type="button" data-test="forceRefresh" onClick={props.forceRefresh} > forceRefresh </button> <button type="button" data-test="exploreChart" onClick={props.logExploreChart} > exploreChart </button> <button type="button" data-test="exportCSV" onClick={props.exportCSV}> exportCSV </button> <button type="button" data-test="handleToggleFullSize" onClick={props.handleToggleFullSize} > handleToggleFullSize </button> <button type="button" data-test="addSuccessToast" onClick={props.addSuccessToast} > addSuccessToast </button> <button type="button" data-test="addDangerToast" onClick={props.addDangerToast} > addDangerToast </button> </div> ), })); jest.mock('src/dashboard/components/FiltersBadge', () => ({ __esModule: true, default: (props: any) => ( <div data-test="FiltersBadge" data-chart-id={props.chartId} /> ), })); const createProps = (overrides: any = {}) => ({ filters: {}, // is in typing but not being used editMode: false, annotationQuery: { param01: 'annotationQuery' } as any, annotationError: { param01: 'annotationError' } as any, cachedDttm: [] as string[], updatedDttm: 1617207718004, isCached: [false], isExpanded: false, sliceName: 'Vaccine Candidates per Phase', supersetCanExplore: true, supersetCanCSV: true, slice: { slice_id: 312, slice_url: '/explore/?form_data=%7B%22slice_id%22%3A%20312%7D', slice_name: 'Vaccine Candidates per Phase', form_data: { adhoc_filters: [], bottom_margin: 'auto', color_scheme: 'SUPERSET_DEFAULT', columns: [], datasource: '58__table', groupby: ['clinical_stage'], label_colors: {}, metrics: ['count'], row_limit: 10000, show_legend: false, time_range: 'No filter', viz_type: 'dist_bar', x_ticks_layout: 'auto', y_axis_format: 'SMART_NUMBER', slice_id: 312, }, viz_type: 'dist_bar', datasource: '58__table', description: '', description_markeddown: '', owners: [], modified: '<span class="no-wrap">20 hours ago</span>', changed_on: 1617143411366, slice_description: '', }, componentId: 'CHART-aGfmWtliqA', dashboardId: 26, isFullSize: false, chartStatus: 'rendered', addSuccessToast: jest.fn(), addDangerToast: jest.fn(), handleToggleFullSize: jest.fn(), updateSliceName: jest.fn(), toggleExpandSlice: jest.fn(), forceRefresh: jest.fn(), logExploreChart: jest.fn(), logEvent: jest.fn(), exportCSV: jest.fn(), formData: { slice_id: 1, datasource: '58__table' }, width: 100, height: 100, ...overrides, }); test('Should render', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByTestId('slice-header')).toBeInTheDocument(); }); test('Should render - default props', () => { const props = createProps(); // @ts-ignore delete props.forceRefresh; // @ts-ignore delete props.updateSliceName; // @ts-ignore delete props.toggleExpandSlice; // @ts-ignore delete props.logExploreChart; // @ts-ignore delete props.exportCSV; // @ts-ignore delete props.innerRef; // @ts-ignore delete props.editMode; // @ts-ignore delete props.annotationQuery; // @ts-ignore delete props.annotationError; // @ts-ignore delete props.cachedDttm; // @ts-ignore delete props.updatedDttm; // @ts-ignore delete props.isCached; // @ts-ignore delete props.isExpanded; // @ts-ignore delete props.sliceName; // @ts-ignore delete props.supersetCanExplore; // @ts-ignore delete props.supersetCanCSV; render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByTestId('slice-header')).toBeInTheDocument(); }); test('Should render default props and "call" actions', () => { const props = createProps(); // @ts-ignore delete props.forceRefresh; // @ts-ignore delete props.updateSliceName; // @ts-ignore delete props.toggleExpandSlice; // @ts-ignore delete props.logExploreChart; // @ts-ignore delete props.exportCSV; // @ts-ignore delete props.innerRef; // @ts-ignore delete props.editMode; // @ts-ignore delete props.annotationQuery; // @ts-ignore delete props.annotationError; // @ts-ignore delete props.cachedDttm; // @ts-ignore delete props.updatedDttm; // @ts-ignore delete props.isCached; // @ts-ignore delete props.isExpanded; // @ts-ignore delete props.sliceName; // @ts-ignore delete props.supersetCanExplore; // @ts-ignore delete props.supersetCanCSV; render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); userEvent.click(screen.getByTestId('toggleExpandSlice')); userEvent.click(screen.getByTestId('forceRefresh')); userEvent.click(screen.getByTestId('exploreChart')); userEvent.click(screen.getByTestId('exportCSV')); userEvent.click(screen.getByTestId('addSuccessToast')); userEvent.click(screen.getByTestId('addDangerToast')); userEvent.click(screen.getByTestId('handleToggleFullSize')); expect(screen.getByTestId('slice-header')).toBeInTheDocument(); }); test('Should render title', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByText('Vaccine Candidates per Phase')).toBeInTheDocument(); }); test('Should render click to edit prompt and run onExploreChart on click', async () => { const props = createProps(); const history = createMemoryHistory({ initialEntries: ['/superset/dashboard/1/'], }); render( <Router history={history}> <SliceHeader {...props} /> </Router>, { useRedux: true }, ); userEvent.hover(screen.getByText('Vaccine Candidates per Phase')); expect( await screen.findByText('Click to edit Vaccine Candidates per Phase.'), ).toBeInTheDocument(); expect( await screen.findByText('Use ctrl + click to open in a new tab.'), ).toBeInTheDocument(); userEvent.click(screen.getByText('Vaccine Candidates per Phase')); expect(history.location.pathname).toMatch('/explore'); }); test('Display cmd button in tooltip if running on MacOS', async () => { jest.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Mac'); const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); userEvent.hover(screen.getByText('Vaccine Candidates per Phase')); expect( await screen.findByText('Click to edit Vaccine Candidates per Phase.'), ).toBeInTheDocument(); expect( await screen.findByText('Use ⌘ + click to open in a new tab.'), ).toBeInTheDocument(); }); test('Should not render click to edit prompt and run onExploreChart on click if supersetCanExplore=false', () => { const props = createProps({ supersetCanExplore: false }); const history = createMemoryHistory({ initialEntries: ['/superset/dashboard/1/'], }); render( <Router history={history}> <SliceHeader {...props} /> </Router>, { useRedux: true }, ); userEvent.hover(screen.getByText('Vaccine Candidates per Phase')); expect( screen.queryByText( 'Click to edit Vaccine Candidates per Phase in a new tab', ), ).not.toBeInTheDocument(); userEvent.click(screen.getByText('Vaccine Candidates per Phase')); expect(history.location.pathname).toMatch('/superset/dashboard'); }); test('Should not render click to edit prompt and run onExploreChart on click if in edit mode', () => { const props = createProps({ editMode: true }); const history = createMemoryHistory({ initialEntries: ['/superset/dashboard/1/'], }); render( <Router history={history}> <SliceHeader {...props} /> </Router>, { useRedux: true }, ); userEvent.hover(screen.getByText('Vaccine Candidates per Phase')); expect( screen.queryByText( 'Click to edit Vaccine Candidates per Phase in a new tab', ), ).not.toBeInTheDocument(); userEvent.click(screen.getByText('Vaccine Candidates per Phase')); expect(history.location.pathname).toMatch('/superset/dashboard'); }); test('Should render "annotationsLoading"', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect( screen.getByRole('img', { name: 'Annotation layers are still loading.', }), ).toBeInTheDocument(); }); test('Should render "annotationsError"', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect( screen.getByRole('img', { name: 'One ore more annotation layers failed loading.', }), ).toBeInTheDocument(); }); test('Should not render "annotationsError" and "annotationsLoading"', () => { const props = createProps(); props.annotationQuery = {}; props.annotationError = {}; render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect( screen.queryByRole('img', { name: 'One ore more annotation layers failed loading.', }), ).not.toBeInTheDocument(); expect( screen.queryByRole('img', { name: 'Annotation layers are still loading.', }), ).not.toBeInTheDocument(); }); test('Correct props to "FiltersBadge"', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByTestId('FiltersBadge')).toHaveAttribute( 'data-chart-id', '312', ); }); test('Correct props to "SliceHeaderControls"', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-cached-dttm', '', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-chart-status', 'rendered', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-component-id', 'CHART-aGfmWtliqA', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-dashboard-id', '26', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-is-cached', 'false', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-is-expanded', 'false', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-is-full-size', 'false', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-superset-can-csv', 'true', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-superset-can-explore', 'true', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-test', 'SliceHeaderControls', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-updated-dttm', '1617207718004', ); expect(screen.getByTestId('SliceHeaderControls')).toHaveAttribute( 'data-slice', JSON.stringify(props.slice), ); }); test('Correct actions to "SliceHeaderControls"', () => { const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(props.toggleExpandSlice).toBeCalledTimes(0); userEvent.click(screen.getByTestId('toggleExpandSlice')); expect(props.toggleExpandSlice).toBeCalledTimes(1); expect(props.forceRefresh).toBeCalledTimes(0); userEvent.click(screen.getByTestId('forceRefresh')); expect(props.forceRefresh).toBeCalledTimes(1); expect(props.logExploreChart).toBeCalledTimes(0); userEvent.click(screen.getByTestId('exploreChart')); expect(props.logExploreChart).toBeCalledTimes(1); expect(props.exportCSV).toBeCalledTimes(0); userEvent.click(screen.getByTestId('exportCSV')); expect(props.exportCSV).toBeCalledTimes(1); expect(props.addSuccessToast).toBeCalledTimes(0); userEvent.click(screen.getByTestId('addSuccessToast')); expect(props.addSuccessToast).toBeCalledTimes(1); expect(props.addDangerToast).toBeCalledTimes(0); userEvent.click(screen.getByTestId('addDangerToast')); expect(props.addDangerToast).toBeCalledTimes(1); expect(props.handleToggleFullSize).toBeCalledTimes(0); userEvent.click(screen.getByTestId('handleToggleFullSize')); expect(props.handleToggleFullSize).toBeCalledTimes(1); }); test('Add extension to SliceHeader', () => { const extensionsRegistry = getExtensionsRegistry(); extensionsRegistry.set('dashboard.slice.header', () => ( <div>This is an extension</div> )); const props = createProps(); render(<SliceHeader {...props} />, { useRedux: true, useRouter: true }); expect(screen.getByText('This is an extension')).toBeInTheDocument(); });
7,164
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/SliceHeaderControls/SliceHeaderControls.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { getMockStore } from 'spec/fixtures/mockStore'; import { render, screen } from 'spec/helpers/testing-library'; import { FeatureFlag } from '@superset-ui/core'; import SliceHeaderControls, { SliceHeaderControlsProps } from '.'; jest.mock('src/components/Dropdown', () => { const original = jest.requireActual('src/components/Dropdown'); return { ...original, NoAnimationDropdown: (props: any) => ( <div data-test="NoAnimationDropdown" className="ant-dropdown"> {props.overlay} {props.children} </div> ), }; }); const createProps = (viz_type = 'sunburst') => ({ addDangerToast: jest.fn(), addSuccessToast: jest.fn(), exploreChart: jest.fn(), exportCSV: jest.fn(), exportFullCSV: jest.fn(), exportXLSX: jest.fn(), exportFullXLSX: jest.fn(), forceRefresh: jest.fn(), handleToggleFullSize: jest.fn(), toggleExpandSlice: jest.fn(), logEvent: jest.fn(), slice: { slice_id: 371, slice_url: '/explore/?form_data=%7B%22slice_id%22%3A%20371%7D', slice_name: 'Vaccine Candidates per Country & Stage', slice_description: 'Table of vaccine candidates for 100 countries', form_data: { adhoc_filters: [], color_scheme: 'supersetColors', datasource: '58__table', groupby: ['product_category', 'clinical_stage'], linear_color_scheme: 'schemeYlOrBr', metric: 'count', queryFields: { groupby: 'groupby', metric: 'metrics', secondary_metric: 'metrics', }, row_limit: 10000, slice_id: 371, time_range: 'No filter', url_params: {}, viz_type, }, viz_type, datasource: '58__table', description: 'test-description', description_markeddown: '', owners: [], modified: '<span class="no-wrap">22 hours ago</span>', changed_on: 1617143411523, }, isCached: [false], isExpanded: false, cachedDttm: [''], updatedDttm: 1617213803803, supersetCanExplore: true, supersetCanCSV: true, componentId: 'CHART-fYo7IyvKZQ', dashboardId: 26, isFullSize: false, chartStatus: 'rendered', showControls: true, supersetCanShare: true, formData: { slice_id: 1, datasource: '58__table', viz_type: 'sunburst' }, exploreUrl: '/explore', } as SliceHeaderControlsProps); const renderWrapper = (overrideProps?: SliceHeaderControlsProps) => { const props = overrideProps || createProps(); const store = getMockStore(); return render(<SliceHeaderControls {...props} />, { useRedux: true, useRouter: true, store, }); }; test('Should render', () => { renderWrapper(); expect( screen.getByRole('button', { name: 'More Options' }), ).toBeInTheDocument(); expect(screen.getByTestId('NoAnimationDropdown')).toBeInTheDocument(); }); test('Should render default props', () => { const props = createProps(); // @ts-ignore delete props.forceRefresh; // @ts-ignore delete props.toggleExpandSlice; // @ts-ignore delete props.exploreChart; // @ts-ignore delete props.exportCSV; // @ts-ignore delete props.exportXLSX; // @ts-ignore delete props.cachedDttm; // @ts-ignore delete props.updatedDttm; // @ts-ignore delete props.isCached; // @ts-ignore delete props.isExpanded; renderWrapper(props); expect( screen.getByRole('menuitem', { name: 'Enter fullscreen' }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: /Force refresh/ }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: 'Show chart description' }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: 'Edit chart' }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: 'Download' }), ).toBeInTheDocument(); expect(screen.getByRole('menuitem', { name: 'Share' })).toBeInTheDocument(); expect( screen.getByRole('button', { name: 'More Options' }), ).toBeInTheDocument(); expect(screen.getByTestId('NoAnimationDropdown')).toBeInTheDocument(); }); test('Should "export to CSV"', async () => { const props = createProps(); renderWrapper(props); expect(props.exportCSV).toBeCalledTimes(0); userEvent.hover(screen.getByText('Download')); userEvent.click(await screen.findByText('Export to .CSV')); expect(props.exportCSV).toBeCalledTimes(1); expect(props.exportCSV).toBeCalledWith(371); }); test('Should "export to Excel"', async () => { const props = createProps(); renderWrapper(props); expect(props.exportXLSX).toBeCalledTimes(0); userEvent.hover(screen.getByText('Download')); userEvent.click(await screen.findByText('Export to Excel')); expect(props.exportXLSX).toBeCalledTimes(1); expect(props.exportXLSX).toBeCalledWith(371); }); test('Should not show "Download" if slice is filter box', () => { const props = createProps('filter_box'); renderWrapper(props); expect(screen.queryByText('Download')).not.toBeInTheDocument(); }); test('Export full CSV is under featureflag', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: false, }; const props = createProps('table'); renderWrapper(props); userEvent.hover(screen.getByText('Download')); expect(await screen.findByText('Export to .CSV')).toBeInTheDocument(); expect(screen.queryByText('Export to full .CSV')).not.toBeInTheDocument(); }); test('Should "export full CSV"', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: true, }; const props = createProps('table'); renderWrapper(props); expect(props.exportFullCSV).toBeCalledTimes(0); userEvent.hover(screen.getByText('Download')); userEvent.click(await screen.findByText('Export to full .CSV')); expect(props.exportFullCSV).toBeCalledTimes(1); expect(props.exportFullCSV).toBeCalledWith(371); }); test('Should not show export full CSV if report is not table', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: true, }; renderWrapper(); userEvent.hover(screen.getByText('Download')); expect(await screen.findByText('Export to .CSV')).toBeInTheDocument(); expect(screen.queryByText('Export to full .CSV')).not.toBeInTheDocument(); }); test('Export full Excel is under featureflag', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: false, }; const props = createProps('table'); renderWrapper(props); userEvent.hover(screen.getByText('Download')); expect(await screen.findByText('Export to Excel')).toBeInTheDocument(); expect(screen.queryByText('Export to full Excel')).not.toBeInTheDocument(); }); test('Should "export full Excel"', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: true, }; const props = createProps('table'); renderWrapper(props); expect(props.exportFullXLSX).toBeCalledTimes(0); userEvent.hover(screen.getByText('Download')); userEvent.click(await screen.findByText('Export to full Excel')); expect(props.exportFullXLSX).toBeCalledTimes(1); expect(props.exportFullXLSX).toBeCalledWith(371); }); test('Should not show export full Excel if report is not table', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.ALLOW_FULL_CSV_EXPORT]: true, }; renderWrapper(); userEvent.hover(screen.getByText('Download')); expect(await screen.findByText('Export to Excel')).toBeInTheDocument(); expect(screen.queryByText('Export to full Excel')).not.toBeInTheDocument(); }); test('Should "Show chart description"', () => { const props = createProps(); renderWrapper(props); expect(props.toggleExpandSlice).toBeCalledTimes(0); userEvent.click(screen.getByText('Show chart description')); expect(props.toggleExpandSlice).toBeCalledTimes(1); expect(props.toggleExpandSlice).toBeCalledWith(371); }); test('Should "Force refresh"', () => { const props = createProps(); renderWrapper(props); expect(props.forceRefresh).toBeCalledTimes(0); userEvent.click(screen.getByText('Force refresh')); expect(props.forceRefresh).toBeCalledTimes(1); expect(props.forceRefresh).toBeCalledWith(371, 26); expect(props.addSuccessToast).toBeCalledTimes(1); }); test('Should "Enter fullscreen"', () => { const props = createProps(); renderWrapper(props); expect(props.handleToggleFullSize).toBeCalledTimes(0); 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(); props.slice.slice_id = 18; renderWrapper(props); expect(screen.getByText('Drill to detail')).toBeInTheDocument(); });
7,166
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/SyncDashboardState/SyncDashboardState.test.tsx
/** * 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 } from 'spec/helpers/testing-library'; import { getItem, LocalStorageKeys } from 'src/utils/localStorageHelpers'; import SyncDashboardState from '.'; test('stores the dashboard info with local storages', () => { const testDashboardPageId = 'dashboardPageId'; render(<SyncDashboardState dashboardPageId={testDashboardPageId} />, { useRedux: true, }); expect(getItem(LocalStorageKeys.dashboard__explore_context, {})).toEqual({ [testDashboardPageId]: expect.objectContaining({ dashboardPageId: testDashboardPageId, }), }); });
7,168
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/URLShortLinkButton/URLShortLinkButton.test.tsx
/** * 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 fetchMock from 'fetch-mock'; import URLShortLinkButton from 'src/dashboard/components/URLShortLinkButton'; import ToastContainer from 'src/components/MessageToasts/ToastContainer'; const DASHBOARD_ID = 10; const PERMALINK_PAYLOAD = { key: '123', url: 'http://fakeurl.com/123', }; const FILTER_STATE_PAYLOAD = { value: '{}', }; const props = { dashboardId: DASHBOARD_ID, }; fetchMock.get( `glob:*/api/v1/dashboard/${DASHBOARD_ID}/filter_state*`, FILTER_STATE_PAYLOAD, ); fetchMock.post( `glob:*/api/v1/dashboard/${DASHBOARD_ID}/permalink`, PERMALINK_PAYLOAD, ); test('renders with default props', () => { render(<URLShortLinkButton {...props} />, { useRedux: true }); expect(screen.getByRole('button')).toBeInTheDocument(); }); test('renders overlay on click', async () => { render(<URLShortLinkButton {...props} />, { useRedux: true }); userEvent.click(screen.getByRole('button')); expect(await screen.findByRole('tooltip')).toBeInTheDocument(); }); test('obtains short url', async () => { render(<URLShortLinkButton {...props} />, { useRedux: true }); userEvent.click(screen.getByRole('button')); expect(await screen.findByRole('tooltip')).toHaveTextContent( PERMALINK_PAYLOAD.url, ); }); test('creates email anchor', async () => { const subject = 'Subject'; const content = 'Content'; render( <URLShortLinkButton {...props} emailSubject={subject} emailContent={content} />, { useRedux: true, }, ); const href = `mailto:?Subject=${subject}%20&Body=${content}${PERMALINK_PAYLOAD.url}`; userEvent.click(screen.getByRole('button')); expect(await screen.findByRole('link')).toHaveAttribute('href', href); }); test('renders error message on short url error', async () => { fetchMock.mock(`glob:*/api/v1/dashboard/${DASHBOARD_ID}/permalink`, 500, { overwriteRoutes: true, }); render( <> <URLShortLinkButton {...props} /> <ToastContainer /> </>, { useRedux: true }, ); userEvent.click(screen.getByRole('button')); expect(await screen.findByRole('alert')).toBeInTheDocument(); });
7,170
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/UndoRedoKeyListeners/UndoRedoKeyListeners.test.tsx
/** * 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, fireEvent } from 'spec/helpers/testing-library'; import UndoRedoKeyListeners from '.'; const defaultProps = { onUndo: jest.fn(), onRedo: jest.fn(), }; test('renders nothing', () => { const { container } = render(<UndoRedoKeyListeners {...defaultProps} />); expect(container.children).toHaveLength(0); }); test('triggers onUndo', () => { const onUndo = jest.fn(); render(<UndoRedoKeyListeners {...defaultProps} onUndo={onUndo} />); fireEvent.keyDown(document.body, { key: 'z', keyCode: 90, ctrlKey: true }); expect(onUndo).toHaveBeenCalledTimes(1); }); test('triggers onRedo', () => { const onRedo = jest.fn(); render(<UndoRedoKeyListeners {...defaultProps} onRedo={onRedo} />); fireEvent.keyDown(document.body, { key: 'y', keyCode: 89, ctrlKey: true }); expect(onRedo).toHaveBeenCalledTimes(1); }); test('does not trigger when it is another key', () => { const onUndo = jest.fn(); const onRedo = jest.fn(); render(<UndoRedoKeyListeners onUndo={onUndo} onRedo={onRedo} />); fireEvent.keyDown(document.body, { key: 'x', keyCode: 88, ctrlKey: true }); expect(onUndo).not.toHaveBeenCalled(); expect(onRedo).not.toHaveBeenCalled(); }); test('removes the event listener when unmounts', () => { document.removeEventListener = jest.fn(); const { unmount } = render(<UndoRedoKeyListeners {...defaultProps} />); unmount(); expect(document.removeEventListener).toHaveBeenCalledWith( 'keydown', expect.anything(), ); });
7,179
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/dnd
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/dnd/handleScroll/handleScroll.test.ts
/** * 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 handleScroll from '.'; jest.useFakeTimers(); const { scroll } = window; afterAll(() => { window.scroll = scroll; }); test('calling: "NOT_SCROLL_TOP" ,"SCROLL_TOP", "NOT_SCROLL_TOP"', () => { window.scroll = jest.fn(); document.documentElement.scrollTop = 500; handleScroll('NOT_SCROLL_TOP'); expect(clearInterval).not.toBeCalled(); handleScroll('SCROLL_TOP'); handleScroll('NOT_SCROLL_TOP'); expect(clearInterval).toHaveBeenCalledWith(expect.any(Number)); });
7,183
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/filterscope/FilterScope.test.tsx
/** * 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 { supersetTheme } from '@superset-ui/core'; import { render, screen } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import FilterScopeSelector from './FilterScopeSelector'; const ROOT_ID = 'ROOT_ID'; const GRID = 'GRID'; const TABS = 'TABS'; const TAB = 'TAB'; const FILTER_A = 'FILTER_A'; const FILTER_B = 'FILTER_B'; const FILTER_C = 'FILTER_C'; const TAB_A = 'TAB_A'; const TAB_B = 'TAB_B'; const CHART_A = 'CHART_A'; const CHART_B = 'CHART_B'; const CHART_C = 'CHART_C'; const CHART_D = 'CHART_D'; const EXPAND_ALL = 'Expand all'; const COLLAPSE_ALL = 'Collapse all'; const CHECKED = 'checked'; const UNCHECKED = 'unchecked'; const INDETERMINATE = 'indeterminate'; const ALL_FILTERS = 'All filters'; const ALL_CHARTS = 'All charts'; const createProps = () => ({ dashboardFilters: { 1: { chartId: 1, componentId: 'component-id', datasourceId: 'datasource-id', directPathToFilter: [], isDateFilter: false, isInstantFilter: false, filterName: FILTER_A, columns: { column_b: undefined, column_c: undefined }, labels: { column_b: FILTER_B, column_c: FILTER_C }, scopes: { column_b: { immune: [], scope: [ROOT_ID] }, column_c: { immune: [], scope: [ROOT_ID] }, }, }, }, layout: { ROOT_ID: { children: [GRID], id: ROOT_ID, type: 'ROOT' }, GRID: { children: [TABS], id: GRID, type: GRID, parents: [ROOT_ID], }, TABS: { children: [TAB_A, TAB_B], id: TABS, type: TABS, parents: [ROOT_ID, GRID], }, TAB_A: { meta: { text: TAB_A }, children: [CHART_A, CHART_B], id: TAB_A, type: TAB, parents: [ROOT_ID, GRID, TABS], }, TAB_B: { meta: { text: TAB_B }, children: [CHART_C, CHART_D], id: TAB_B, type: TAB, parents: [ROOT_ID, GRID, TABS], }, CHART_A: { meta: { chartId: 2, sliceName: CHART_A, }, children: [], id: CHART_A, type: 'CHART', parents: [ROOT_ID, GRID, TABS, TAB_A], }, CHART_B: { meta: { chartId: 3, sliceName: CHART_B, }, children: [], id: CHART_B, type: 'CHART', parents: [ROOT_ID, GRID, TABS, TAB_A], }, CHART_C: { meta: { chartId: 4, sliceName: CHART_C, }, children: [], id: CHART_C, type: 'CHART', parents: [ROOT_ID, GRID, TABS, TAB_B], }, CHART_D: { meta: { chartId: 5, sliceName: CHART_D, }, children: [], id: CHART_D, type: 'CHART', parents: [ROOT_ID, GRID, TABS, TAB_B], }, }, updateDashboardFiltersScope: jest.fn(), setUnsavedChanges: jest.fn(), onCloseModal: jest.fn(), }); type CheckboxState = 'checked' | 'unchecked' | 'indeterminate'; /** * Unfortunately react-checkbox-tree doesn't provide an easy way to * access the checkbox icon. We need this function to find the element. */ function getCheckboxIcon(element: HTMLElement): Element { const parent = element.parentElement!; if (parent.classList.contains('rct-text')) { return parent.children[1]; } return getCheckboxIcon(parent); } /** * Unfortunately when using react-checkbox-tree, the only perceived change of a * checkbox state change is the fill color of the SVG icon. */ function getCheckboxState(name: string): CheckboxState { const element = screen.getByRole('link', { name }); const svgPath = getCheckboxIcon(element).children[1].children[0].children[0]; const fill = svgPath.getAttribute('fill'); return fill === supersetTheme.colors.primary.base ? CHECKED : fill === supersetTheme.colors.grayscale.light1 ? INDETERMINATE : UNCHECKED; } function clickCheckbox(name: string) { const element = screen.getByRole('link', { name }); const checkboxLabel = getCheckboxIcon(element); userEvent.click(checkboxLabel); } test('renders with empty filters', () => { render(<FilterScopeSelector {...createProps()} dashboardFilters={{}} />, { useRedux: true, }); expect(screen.getByText('Configure filter scopes')).toBeInTheDocument(); expect( screen.getByText('There are no filters in this dashboard.'), ).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Save' }), ).not.toBeInTheDocument(); }); test('renders with filters values', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true }); expect(screen.getByRole('link', { name: FILTER_A })).toBeInTheDocument(); expect(screen.getByRole('link', { name: FILTER_B })).toBeInTheDocument(); expect(screen.getByRole('link', { name: FILTER_C })).toBeInTheDocument(); expect(screen.getByRole('link', { name: TAB_A })).toBeInTheDocument(); expect(screen.getByRole('link', { name: TAB_B })).toBeInTheDocument(); expect(screen.queryByText(CHART_A)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_B)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_C)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_D)).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument(); }); test('collapses/expands all filters', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.click(screen.getAllByRole('button', { name: COLLAPSE_ALL })[0]); expect(screen.getByRole('link', { name: ALL_FILTERS })).toBeInTheDocument(); expect( screen.queryByRole('link', { name: FILTER_A }), ).not.toBeInTheDocument(); expect( screen.queryByRole('link', { name: FILTER_B }), ).not.toBeInTheDocument(); expect( screen.queryByRole('link', { name: FILTER_C }), ).not.toBeInTheDocument(); userEvent.click(screen.getAllByRole('button', { name: EXPAND_ALL })[0]); expect(screen.getByRole('link', { name: ALL_FILTERS })).toBeInTheDocument(); expect(screen.getByRole('link', { name: FILTER_A })).toBeInTheDocument(); expect(screen.getByRole('link', { name: FILTER_B })).toBeInTheDocument(); expect(screen.getByRole('link', { name: FILTER_C })).toBeInTheDocument(); }); test('collapses/expands all charts', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.click(screen.getAllByRole('button', { name: COLLAPSE_ALL })[1]); expect(screen.getByText(ALL_CHARTS)).toBeInTheDocument(); expect(screen.queryByText(CHART_A)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_B)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_C)).not.toBeInTheDocument(); expect(screen.queryByText(CHART_D)).not.toBeInTheDocument(); userEvent.click(screen.getAllByRole('button', { name: EXPAND_ALL })[1]); expect(screen.getByText(ALL_CHARTS)).toBeInTheDocument(); expect(screen.getByRole('link', { name: CHART_A })).toBeInTheDocument(); expect(screen.getByRole('link', { name: CHART_B })).toBeInTheDocument(); expect(screen.getByRole('link', { name: CHART_C })).toBeInTheDocument(); expect(screen.getByRole('link', { name: CHART_D })).toBeInTheDocument(); }); test('searches for a chart', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.type(screen.getByPlaceholderText('Search...'), CHART_C); expect(screen.queryByRole('link', { name: CHART_A })).not.toBeInTheDocument(); expect(screen.queryByRole('link', { name: CHART_B })).not.toBeInTheDocument(); expect(screen.getByRole('link', { name: CHART_C })).toBeInTheDocument(); }); test('selects a leaf filter', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); expect(getCheckboxState(FILTER_C)).toBe(UNCHECKED); clickCheckbox(FILTER_C); expect(getCheckboxState(FILTER_C)).toBe(CHECKED); }); test('selects a leaf chart', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.click(screen.getAllByRole('button', { name: EXPAND_ALL })[1]); expect(getCheckboxState(CHART_D)).toBe(UNCHECKED); clickCheckbox(CHART_D); expect(getCheckboxState(CHART_D)).toBe(CHECKED); }); test('selects a branch of filters', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); expect(getCheckboxState(FILTER_A)).toBe(UNCHECKED); expect(getCheckboxState(FILTER_B)).toBe(UNCHECKED); expect(getCheckboxState(FILTER_C)).toBe(UNCHECKED); clickCheckbox(FILTER_A); expect(getCheckboxState(FILTER_A)).toBe(CHECKED); expect(getCheckboxState(FILTER_B)).toBe(CHECKED); expect(getCheckboxState(FILTER_C)).toBe(CHECKED); }); test('selects a branch of charts', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); const tabA = screen.getByText(TAB_A); userEvent.click(tabA); expect(getCheckboxState(TAB_A)).toBe(UNCHECKED); expect(getCheckboxState(CHART_A)).toBe(UNCHECKED); expect(getCheckboxState(CHART_B)).toBe(UNCHECKED); clickCheckbox(TAB_A); expect(getCheckboxState(TAB_A)).toBe(CHECKED); expect(getCheckboxState(CHART_A)).toBe(CHECKED); expect(getCheckboxState(CHART_B)).toBe(CHECKED); }); test('selects all filters', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.click(screen.getAllByRole('button', { name: EXPAND_ALL })[0]); expect(getCheckboxState(ALL_FILTERS)).toBe(UNCHECKED); expect(getCheckboxState(FILTER_A)).toBe(UNCHECKED); expect(getCheckboxState(FILTER_B)).toBe(UNCHECKED); expect(getCheckboxState(FILTER_C)).toBe(UNCHECKED); clickCheckbox(ALL_FILTERS); expect(getCheckboxState(ALL_FILTERS)).toBe(CHECKED); expect(getCheckboxState(FILTER_A)).toBe(CHECKED); expect(getCheckboxState(FILTER_B)).toBe(CHECKED); expect(getCheckboxState(FILTER_C)).toBe(CHECKED); }); test('selects all charts', () => { render(<FilterScopeSelector {...createProps()} />, { useRedux: true, }); userEvent.click(screen.getAllByRole('button', { name: EXPAND_ALL })[1]); expect(getCheckboxState(TAB_A)).toBe(UNCHECKED); expect(getCheckboxState(CHART_A)).toBe(UNCHECKED); expect(getCheckboxState(CHART_B)).toBe(UNCHECKED); expect(getCheckboxState(TAB_B)).toBe(UNCHECKED); expect(getCheckboxState(CHART_C)).toBe(UNCHECKED); expect(getCheckboxState(CHART_D)).toBe(UNCHECKED); clickCheckbox(ALL_CHARTS); expect(getCheckboxState(TAB_A)).toBe(CHECKED); expect(getCheckboxState(CHART_A)).toBe(CHECKED); expect(getCheckboxState(CHART_B)).toBe(CHECKED); expect(getCheckboxState(TAB_B)).toBe(CHECKED); expect(getCheckboxState(CHART_C)).toBe(CHECKED); expect(getCheckboxState(CHART_D)).toBe(CHECKED); }); test('triggers onClose', () => { const onCloseModal = jest.fn(); render( <FilterScopeSelector {...createProps()} onCloseModal={onCloseModal} />, { useRedux: true, }, ); expect(onCloseModal).toHaveBeenCalledTimes(0); userEvent.click(screen.getByRole('button', { name: 'Close' })); expect(onCloseModal).toHaveBeenCalledTimes(1); }); test('triggers onSave', () => { const updateDashboardFiltersScope = jest.fn(); const setUnsavedChanges = jest.fn(); const onCloseModal = jest.fn(); render( <FilterScopeSelector {...createProps()} updateDashboardFiltersScope={updateDashboardFiltersScope} setUnsavedChanges={setUnsavedChanges} onCloseModal={onCloseModal} />, { useRedux: true, }, ); expect(updateDashboardFiltersScope).toHaveBeenCalledTimes(0); expect(setUnsavedChanges).toHaveBeenCalledTimes(0); expect(onCloseModal).toHaveBeenCalledTimes(0); userEvent.click(screen.getByRole('button', { name: 'Save' })); expect(updateDashboardFiltersScope).toHaveBeenCalledTimes(1); expect(setUnsavedChanges).toHaveBeenCalledTimes(1); expect(onCloseModal).toHaveBeenCalledTimes(1); });
7,192
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/gridComponents/ChartHolder.test.tsx
/** * 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 { combineReducers, createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import sinon from 'sinon'; import userEvent from '@testing-library/user-event'; import mockState from 'spec/fixtures/mockState'; import reducerIndex from 'spec/helpers/reducerIndex'; import { sliceId as chartId } from 'spec/fixtures/mockChartQueries'; import { screen, render, waitFor, fireEvent, } from 'spec/helpers/testing-library'; import { nativeFiltersInfo } from 'src/dashboard/fixtures/mockNativeFilters'; import newComponentFactory from 'src/dashboard/util/newComponentFactory'; import { initialState } from 'src/SqlLab/fixtures'; import { SET_DIRECT_PATH } from 'src/dashboard/actions/dashboardState'; import { CHART_TYPE, COLUMN_TYPE, ROW_TYPE } from '../../util/componentTypes'; import ChartHolder, { CHART_MARGIN } from './ChartHolder'; import { GRID_BASE_UNIT, GRID_GUTTER_SIZE } from '../../util/constants'; const DEFAULT_HEADER_HEIGHT = 22; describe('ChartHolder', () => { let scrollViewBase: any; const defaultProps = { component: { ...newComponentFactory(CHART_TYPE), id: 'CHART-ID', parents: ['ROOT_ID', 'TABS_ID', 'TAB_ID', 'ROW_ID'], meta: { uuid: `CHART-${chartId}`, chartId, width: 3, height: 10, chartName: 'Mock chart name', }, }, parentComponent: { ...newComponentFactory(ROW_TYPE), id: 'ROW_ID', children: ['COLUMN_ID'], }, index: 0, depth: 0, id: 'CHART-ID', parentId: 'ROW_ID', availableColumnCount: 12, columnWidth: 300, onResizeStart: () => {}, onResize: () => {}, onResizeStop: () => {}, handleComponentDrop: () => {}, deleteComponent: () => {}, updateComponents: () => {}, editMode: false, isComponentVisible: true, dashboardId: 123, nativeFilters: nativeFiltersInfo.filters, fullSizeChartId: chartId, setFullSizeChartId: () => {}, }; beforeAll(() => { scrollViewBase = window.HTMLElement.prototype.scrollIntoView; window.HTMLElement.prototype.scrollIntoView = () => {}; }); afterAll(() => { window.HTMLElement.prototype.scrollIntoView = scrollViewBase; }); const createMockStore = (customState: any = {}) => createStore( combineReducers(reducerIndex), { ...mockState, ...(initialState as any), ...customState }, compose(applyMiddleware(thunk)), ); const renderWrapper = (store = createMockStore(), props: any = {}) => render(<ChartHolder {...defaultProps} {...props} />, { useRouter: true, useDnd: true, useRedux: true, store, }); it('should render empty state', async () => { renderWrapper(); expect( screen.getByText('No results were returned for this query'), ).toBeVisible(); expect( screen.queryByText( 'Make sure that the controls are configured properly and the datasource contains data for the selected time range', ), ).not.toBeInTheDocument(); // description should display only in Explore view expect(screen.getByAltText('empty')).toBeVisible(); }); it('should render anchor link when not editing', async () => { const store = createMockStore(); const { rerender } = renderWrapper(store, { editMode: false }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); expect( screen .getByTestId('dashboard-component-chart-holder') .getElementsByClassName('anchor-link-container').length, ).toEqual(1); rerender( <Provider store={store}> <ChartHolder {...defaultProps} editMode isInView /> </Provider>, ); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); expect( screen .getByTestId('dashboard-component-chart-holder') .getElementsByClassName('anchor-link-container').length, ).toEqual(0); }); it('should highlight when path matches', async () => { const store = createMockStore({ dashboardState: { ...mockState.dashboardState, directPathToChild: ['CHART-ID'], }, }); renderWrapper(store); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); expect(screen.getByTestId('dashboard-component-chart-holder')).toHaveClass( 'fade-out', ); expect( screen.getByTestId('dashboard-component-chart-holder'), ).not.toHaveClass('fade-in'); store.dispatch({ type: SET_DIRECT_PATH, path: ['CHART-ID'] }); await waitFor(() => { expect( screen.getByTestId('dashboard-component-chart-holder'), ).not.toHaveClass('fade-out'); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toHaveClass('fade-in'); }); await waitFor( () => { expect( screen.getByTestId('dashboard-component-chart-holder'), ).toHaveClass('fade-out'); expect( screen.getByTestId('dashboard-component-chart-holder'), ).not.toHaveClass('fade-in'); }, { timeout: 5000 }, ); }); it('should calculate the default widthMultiple', async () => { const widthMultiple = 5; renderWrapper(createMockStore(), { editMode: true, component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, width: widthMultiple, }, }, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const resizeContainer = screen .getByTestId('dragdroppable-object') .getElementsByClassName('resizable-container')[0]; const { width: computedWidth } = getComputedStyle(resizeContainer); const expectedWidth = (defaultProps.columnWidth + GRID_GUTTER_SIZE) * widthMultiple - GRID_GUTTER_SIZE; expect(computedWidth).toEqual(`${expectedWidth}px`); }); it('should set the resizable width to auto when parent component type is column', async () => { renderWrapper(createMockStore(), { editMode: true, parentComponent: { ...newComponentFactory(COLUMN_TYPE), id: 'ROW_ID', children: ['COLUMN_ID'], }, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const resizeContainer = screen .getByTestId('dragdroppable-object') .getElementsByClassName('resizable-container')[0]; const { width: computedWidth } = getComputedStyle(resizeContainer); // the width is only adjustable if the parent component is row type expect(computedWidth).toEqual('auto'); }); it("should override the widthMultiple if there's a column in the parent chain whose width is less than the chart", async () => { const widthMultiple = 10; const parentColumnWidth = 6; renderWrapper(createMockStore(), { editMode: true, component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, width: widthMultiple, }, }, // Return the first column in the chain getComponentById: () => newComponentFactory(COLUMN_TYPE, { width: parentColumnWidth }), }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const resizeContainer = screen .getByTestId('dragdroppable-object') .getElementsByClassName('resizable-container')[0]; const { width: computedWidth } = getComputedStyle(resizeContainer); const expectedWidth = (defaultProps.columnWidth + GRID_GUTTER_SIZE) * parentColumnWidth - GRID_GUTTER_SIZE; expect(computedWidth).toEqual(`${expectedWidth}px`); }); it('should calculate the chartWidth', async () => { const widthMultiple = 7; const columnWidth = 250; renderWrapper(createMockStore(), { fullSizeChartId: null, component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, width: widthMultiple, }, }, columnWidth, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const container = screen.getByTestId('chart-container'); const computedWidth = parseInt(container.getAttribute('width') || '0', 10); const expectedWidth = Math.floor( widthMultiple * columnWidth + (widthMultiple - 1) * GRID_GUTTER_SIZE - CHART_MARGIN, ); expect(computedWidth).toEqual(expectedWidth); }); it('should calculate the chartWidth on full screen mode', async () => { const widthMultiple = 7; const columnWidth = 250; renderWrapper(createMockStore(), { component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, width: widthMultiple, }, }, columnWidth, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const container = screen.getByTestId('chart-container'); const computedWidth = parseInt(container.getAttribute('width') || '0', 10); const expectedWidth = window.innerWidth - CHART_MARGIN; expect(computedWidth).toEqual(expectedWidth); }); it('should calculate the chartHeight', async () => { const heightMultiple = 12; renderWrapper(createMockStore(), { fullSizeChartId: null, component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, height: heightMultiple, }, }, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const container = screen.getByTestId('chart-container'); const computedWidth = parseInt(container.getAttribute('height') || '0', 10); const expectedWidth = Math.floor( heightMultiple * GRID_BASE_UNIT - CHART_MARGIN - DEFAULT_HEADER_HEIGHT, ); expect(computedWidth).toEqual(expectedWidth); }); it('should calculate the chartHeight on full screen mode', async () => { const heightMultiple = 12; renderWrapper(createMockStore(), { component: { ...defaultProps.component, meta: { ...defaultProps.component.meta, height: heightMultiple, }, }, }); expect( screen.getByTestId('dashboard-component-chart-holder'), ).toBeVisible(); const container = screen.getByTestId('chart-container'); const computedWidth = parseInt(container.getAttribute('height') || '0', 10); const expectedWidth = window.innerHeight - CHART_MARGIN - DEFAULT_HEADER_HEIGHT; expect(computedWidth).toEqual(expectedWidth); }); it('should call deleteComponent when deleted', async () => { const deleteComponent = sinon.spy(); const store = createMockStore(); const { rerender } = renderWrapper(store, { editMode: false, fullSizeChartId: null, deleteComponent, }); expect( screen.queryByTestId('dashboard-delete-component-button'), ).not.toBeInTheDocument(); rerender( <Provider store={store}> <ChartHolder {...defaultProps} deleteComponent={deleteComponent} fullSizeChartId={null} editMode isInView /> </Provider>, ); expect( screen.getByTestId('dashboard-delete-component-button'), ).toBeInTheDocument(); userEvent.hover(screen.getByTestId('dashboard-component-chart-holder')); fireEvent.click( screen.getByTestId('dashboard-delete-component-button') .firstElementChild!, ); expect(deleteComponent.callCount).toBe(1); }); });
7,207
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/gridComponents/Tab.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import DashboardComponent from 'src/dashboard/containers/DashboardComponent'; import EditableTitle from 'src/components/EditableTitle'; import DragDroppable from 'src/dashboard/components/dnd/DragDroppable'; import { setEditMode } from 'src/dashboard/actions/dashboardState'; import Tab from './Tab'; jest.mock('src/dashboard/containers/DashboardComponent', () => jest.fn(() => <div data-test="DashboardComponent" />), ); jest.mock('src/components/EditableTitle', () => jest.fn(props => ( <button type="button" data-test="EditableTitle" onClick={props.onSaveTitle}> {props.title} </button> )), ); jest.mock('src/dashboard/components/dnd/DragDroppable', () => jest.fn(props => { const childProps = props.editMode ? { dragSourceRef: props.dragSourceRef, dropIndicatorProps: props.dropIndicatorProps, } : {}; return ( <div> <button type="button" data-test="DragDroppable" onClick={props.onDrop}> DragDroppable </button> {props.children(childProps)} </div> ); }), ); jest.mock('src/dashboard/actions/dashboardState', () => ({ setEditMode: jest.fn(() => ({ type: 'SET_EDIT_MODE', })), })); const createProps = () => ({ id: 'TAB-YT6eNksV-', parentId: 'TABS-L-d9eyOE-b', depth: 2, index: 1, renderType: 'RENDER_TAB_CONTENT', availableColumnCount: 12, columnWidth: 120, isFocused: false, component: { children: ['ROW-DR80aHJA2c', 'ROW--BIzjz9F0'], id: 'TAB-YT6eNksV-', meta: { text: '🚀 Aspiring Developers' }, parents: ['ROOT_ID', 'GRID_ID', 'TABS-L-d9eyOE-b'], type: 'TAB', }, parentComponent: { children: ['TAB-AsMaxdYL_t', 'TAB-YT6eNksV-', 'TAB-l_9I0aNYZ'], id: 'TABS-L-d9eyOE-b', meta: {}, parents: ['ROOT_ID', 'GRID_ID'], type: 'TABS', }, editMode: false, undoLength: 0, redoLength: 0, filters: {}, directPathToChild: ['ROOT_ID', 'GRID_ID', 'TABS-L-d9eyOE-b', 'TAB-YT6eNksV-'], directPathLastUpdated: 1617374760080, dashboardId: 23, focusedFilterScope: null, isComponentVisible: true, onDropOnTab: jest.fn(), handleComponentDrop: jest.fn(), updateComponents: jest.fn(), setDirectPathToChild: jest.fn(), }); beforeEach(() => { jest.clearAllMocks(); }); test('Render tab (no content)', () => { const props = createProps(); props.renderType = 'RENDER_TAB'; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(screen.getByText('🚀 Aspiring Developers')).toBeInTheDocument(); expect(EditableTitle).toBeCalledTimes(1); expect(DragDroppable).toBeCalledTimes(1); }); test('Render tab (no content) editMode:true', () => { const props = createProps(); props.editMode = true; props.renderType = 'RENDER_TAB'; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(screen.getByText('🚀 Aspiring Developers')).toBeInTheDocument(); expect(EditableTitle).toBeCalledTimes(1); expect(DragDroppable).toBeCalledTimes(1); }); test('Edit table title', () => { const props = createProps(); props.editMode = true; props.renderType = 'RENDER_TAB'; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(EditableTitle).toBeCalledTimes(1); expect(DragDroppable).toBeCalledTimes(1); expect(props.updateComponents).not.toBeCalled(); userEvent.click(screen.getByText('🚀 Aspiring Developers')); expect(props.updateComponents).toBeCalled(); }); test('Render tab (with content)', () => { const props = createProps(); props.isFocused = true; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(DashboardComponent).toBeCalledTimes(2); expect(DashboardComponent).toHaveBeenNthCalledWith( 1, expect.objectContaining({ availableColumnCount: 12, columnWidth: 120, depth: 2, id: 'ROW-DR80aHJA2c', index: 0, isComponentVisible: true, onChangeTab: expect.any(Function), onDrop: expect.any(Function), onResize: expect.any(Function), onResizeStart: expect.any(Function), onResizeStop: expect.any(Function), parentId: 'TAB-YT6eNksV-', }), {}, ); expect(DashboardComponent).toHaveBeenNthCalledWith( 2, expect.objectContaining({ availableColumnCount: 12, columnWidth: 120, depth: 2, id: 'ROW--BIzjz9F0', index: 1, isComponentVisible: true, onChangeTab: expect.any(Function), onDrop: expect.any(Function), onResize: expect.any(Function), onResizeStart: expect.any(Function), onResizeStop: expect.any(Function), parentId: 'TAB-YT6eNksV-', }), {}, ); expect(DragDroppable).toBeCalledTimes(0); }); test('Render tab content with no children', () => { const props = createProps(); props.component.children = []; render(<Tab {...props} />, { useRedux: true, useDnd: true, }); expect( screen.getByText('There are no components added to this tab'), ).toBeVisible(); expect(screen.getByAltText('empty')).toBeVisible(); expect(screen.queryByText('edit mode')).not.toBeInTheDocument(); }); test('Render tab content with no children, canEdit: true', () => { const props = createProps(); props.component.children = []; render(<Tab {...props} />, { useRedux: true, useDnd: true, initialState: { dashboardInfo: { dash_edit_perm: true, }, }, }); expect(screen.getByText('edit mode')).toBeVisible(); userEvent.click(screen.getByRole('button', { name: 'edit mode' })); expect(setEditMode).toHaveBeenCalled(); }); test('Render tab (with content) editMode:true', () => { const props = createProps(); props.isFocused = true; props.editMode = true; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(DashboardComponent).toBeCalledTimes(2); expect(DashboardComponent).toHaveBeenNthCalledWith( 1, expect.objectContaining({ availableColumnCount: 12, columnWidth: 120, depth: 2, id: 'ROW-DR80aHJA2c', index: 0, isComponentVisible: true, onChangeTab: expect.any(Function), onDrop: expect.any(Function), onResize: expect.any(Function), onResizeStart: expect.any(Function), onResizeStop: expect.any(Function), parentId: 'TAB-YT6eNksV-', }), {}, ); expect(DashboardComponent).toHaveBeenNthCalledWith( 2, expect.objectContaining({ availableColumnCount: 12, columnWidth: 120, depth: 2, id: 'ROW--BIzjz9F0', index: 1, isComponentVisible: true, onChangeTab: expect.any(Function), onDrop: expect.any(Function), onResize: expect.any(Function), onResizeStart: expect.any(Function), onResizeStop: expect.any(Function), parentId: 'TAB-YT6eNksV-', }), {}, ); expect(DragDroppable).toBeCalledTimes(2); }); test('Should call "handleDrop" and "handleTopDropTargetDrop"', () => { const props = createProps(); props.isFocused = true; props.editMode = true; render(<Tab {...props} />, { useRedux: true, useDnd: true }); expect(props.handleComponentDrop).not.toBeCalled(); userEvent.click(screen.getAllByRole('button')[0]); expect(props.handleComponentDrop).toBeCalledTimes(1); expect(props.onDropOnTab).not.toBeCalled(); userEvent.click(screen.getAllByRole('button')[1]); expect(props.onDropOnTab).toBeCalledTimes(1); expect(props.handleComponentDrop).toBeCalledTimes(2); }); test('Render tab content with no children, editMode: true, canEdit: true', () => { const props = createProps(); props.editMode = true; // props.canEdit = true; props.component.children = []; render(<Tab {...props} />, { useRedux: true, useDnd: true, initialState: { dashboardInfo: { dash_edit_perm: true, }, }, }); expect( screen.getByText('Drag and drop components to this tab'), ).toBeVisible(); expect(screen.getByAltText('empty')).toBeVisible(); expect( screen.getByRole('link', { name: 'create a new chart' }), ).toBeVisible(); expect( screen.getByRole('link', { name: 'create a new chart' }), ).toHaveAttribute('href', '/chart/add?dashboard_id=23'); });
7,210
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/gridComponents/Tabs.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import { nativeFiltersInfo } from 'src/dashboard/fixtures/mockNativeFilters'; import DashboardComponent from 'src/dashboard/containers/DashboardComponent'; import DragDroppable from 'src/dashboard/components/dnd/DragDroppable'; import DeleteComponentButton from 'src/dashboard/components/DeleteComponentButton'; import getLeafComponentIdFromPath from 'src/dashboard/util/getLeafComponentIdFromPath'; import emptyDashboardLayout from 'src/dashboard/fixtures/emptyDashboardLayout'; import { Tabs } from './Tabs'; jest.mock('src/dashboard/containers/DashboardComponent', () => jest.fn(props => ( <button type="button" onClick={() => props.onDropOnTab({ destination: { id: 'TAB-YT6eNksV-' } }) } data-test="DashboardComponent" > DashboardComponent </button> )), ); jest.mock('src/dashboard/components/DeleteComponentButton', () => jest.fn(props => ( <button type="button" data-test="DeleteComponentButton" onClick={props.onDelete} > DeleteComponentButton </button> )), ); jest.mock('src/dashboard/util/getLeafComponentIdFromPath', () => jest.fn()); jest.mock('src/dashboard/components/dnd/DragDroppable', () => jest.fn(props => { const childProps = props.editMode ? { dragSourceRef: props.dragSourceRef, dropIndicatorProps: props.dropIndicatorProps, } : {}; return ( <div> <button type="button" data-test="DragDroppable" onClick={props.onDrop}> DragDroppable </button> {props.children(childProps)} </div> ); }), ); const createProps = () => ({ id: 'TABS-L-d9eyOE-b', parentId: 'GRID_ID', depth: 2, index: 0, availableColumnCount: 12, columnWidth: 120, isComponentVisible: true, component: { children: ['TAB-AsMaxdYL_t', 'TAB-YT6eNksV-', 'TAB-l_9I0aNYZ'], id: 'TABS-L-d9eyOE-b', meta: {}, parents: ['ROOT_ID', 'GRID_ID'], type: 'TABS', }, parentComponent: { children: ['TABS-L-d9eyOE-b'], id: 'GRID_ID', parents: ['ROOT_ID'], type: 'GRID', }, editMode: true, undoLength: 0, redoLength: 0, filters: {}, directPathToChild: [], directPathLastUpdated: 1617395480760, dashboardId: 23, focusedFilterScope: null, renderTabContent: true, renderHoverMenu: true, logEvent: jest.fn(), createComponent: jest.fn(), handleComponentDrop: jest.fn(), onChangeTab: jest.fn(), deleteComponent: jest.fn(), updateComponents: jest.fn(), dashboardLayout: emptyDashboardLayout, nativeFilters: nativeFiltersInfo.filters, }); beforeEach(() => { jest.clearAllMocks(); }); test('Should render editMode:true', () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true }); expect(screen.getAllByRole('tab')).toHaveLength(3); expect(DragDroppable).toBeCalledTimes(1); expect(DashboardComponent).toBeCalledTimes(4); expect(DeleteComponentButton).toBeCalledTimes(1); expect(screen.getAllByRole('button', { name: 'remove' })).toHaveLength(3); expect(screen.getAllByRole('button', { name: 'Add tab' })).toHaveLength(2); }); test('Should render editMode:false', () => { const props = createProps(); props.editMode = false; render(<Tabs {...props} />, { useRedux: true, useDnd: true }); expect(screen.getAllByRole('tab')).toHaveLength(3); expect(DragDroppable).toBeCalledTimes(1); expect(DashboardComponent).toBeCalledTimes(4); expect(DeleteComponentButton).not.toBeCalled(); expect( screen.queryByRole('button', { name: 'remove' }), ).not.toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Add tab' }), ).not.toBeInTheDocument(); }); test('Update component props', () => { const props = createProps(); (getLeafComponentIdFromPath as jest.Mock).mockResolvedValueOnce('none'); props.editMode = false; const { rerender } = render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(DeleteComponentButton).not.toBeCalled(); props.editMode = true; rerender(<Tabs {...props} />); expect(DeleteComponentButton).toBeCalledTimes(1); }); test('Clicking on "DeleteComponentButton"', () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(props.deleteComponent).not.toBeCalled(); userEvent.click(screen.getByTestId('DeleteComponentButton')); expect(props.deleteComponent).toBeCalledWith('TABS-L-d9eyOE-b', 'GRID_ID'); }); test('Add new tab', () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(props.createComponent).not.toBeCalled(); userEvent.click(screen.getAllByRole('button', { name: 'Add tab' })[0]); expect(props.createComponent).toBeCalled(); }); test('Removing a tab', async () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(props.deleteComponent).not.toBeCalled(); expect(screen.queryByText('Delete dashboard tab?')).not.toBeInTheDocument(); userEvent.click(screen.getAllByRole('button', { name: 'remove' })[0]); expect(props.deleteComponent).not.toBeCalled(); expect(await screen.findByText('Delete dashboard tab?')).toBeInTheDocument(); expect(props.deleteComponent).not.toBeCalled(); userEvent.click(screen.getByRole('button', { name: 'DELETE' })); expect(props.deleteComponent).toBeCalled(); }); test('Switching tabs', () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(props.logEvent).not.toBeCalled(); expect(props.onChangeTab).not.toBeCalled(); userEvent.click(screen.getAllByRole('tab')[2]); expect(props.logEvent).toBeCalled(); expect(props.onChangeTab).toBeCalled(); }); test('Call "DashboardComponent.onDropOnTab"', async () => { const props = createProps(); render(<Tabs {...props} />, { useRedux: true, useDnd: true, }); expect(props.logEvent).not.toBeCalled(); expect(props.onChangeTab).not.toBeCalled(); userEvent.click(screen.getAllByText('DashboardComponent')[0]); await waitFor(() => { expect(props.logEvent).toBeCalled(); expect(props.onChangeTab).toBeCalled(); }); });
7,227
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu/HoverMenu.test.tsx
/** * 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 { shallow } from 'enzyme'; import HoverMenu from 'src/dashboard/components/menu/HoverMenu'; describe('HoverMenu', () => { it('should render a div.hover-menu', () => { const wrapper = shallow(<HoverMenu />); expect(wrapper.find('.hover-menu')).toExist(); }); });
7,232
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadAsImage.test.tsx
import React, { SyntheticEvent } from 'react'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import { Menu } from 'src/components/Menu'; import downloadAsImage from 'src/utils/downloadAsImage'; import DownloadAsImage from './DownloadAsImage'; jest.mock('src/utils/downloadAsImage', () => ({ __esModule: true, default: jest.fn(() => (_e: SyntheticEvent) => {}), })); const createProps = () => ({ addDangerToast: jest.fn(), text: 'Download as Image', dashboardTitle: 'Test Dashboard', logEvent: jest.fn(), }); const renderComponent = () => { render( <Menu> <DownloadAsImage {...createProps()} /> </Menu>, ); }; test('Should call download image on click', async () => { const props = createProps(); renderComponent(); await waitFor(() => { expect(downloadAsImage).toBeCalledTimes(0); expect(props.addDangerToast).toBeCalledTimes(0); }); userEvent.click(screen.getByRole('button', { name: 'Download as Image' })); await waitFor(() => { expect(downloadAsImage).toBeCalledTimes(1); expect(props.addDangerToast).toBeCalledTimes(0); }); });
7,234
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadAsPdf.test.tsx
import React, { SyntheticEvent } from 'react'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import { Menu } from 'src/components/Menu'; import downloadAsPdf from 'src/utils/downloadAsPdf'; import DownloadAsPdf from './DownloadAsPdf'; jest.mock('src/utils/downloadAsPdf', () => ({ __esModule: true, default: jest.fn(() => (_e: SyntheticEvent) => {}), })); const createProps = () => ({ addDangerToast: jest.fn(), text: 'Export as PDF', dashboardTitle: 'Test Dashboard', logEvent: jest.fn(), }); const renderComponent = () => { render( <Menu> <DownloadAsPdf {...createProps()} /> </Menu>, ); }; test('Should call download pdf on click', async () => { const props = createProps(); renderComponent(); await waitFor(() => { expect(downloadAsPdf).toBeCalledTimes(0); expect(props.addDangerToast).toBeCalledTimes(0); }); userEvent.click(screen.getByRole('button', { name: 'Export as PDF' })); await waitFor(() => { expect(downloadAsPdf).toBeCalledTimes(1); expect(props.addDangerToast).toBeCalledTimes(0); }); });
7,236
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadMenuItems.test.tsx
import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import DownloadMenuItems from '.'; const createProps = () => ({ addDangerToast: jest.fn(), pdfMenuItemTitle: 'Export to PDF', imageMenuItemTitle: 'Download as Image', dashboardTitle: 'Test Dashboard', logEvent: jest.fn(), }); const renderComponent = () => { render(<DownloadMenuItems {...createProps()} />); }; test('Should render menu items', () => { renderComponent(); expect( screen.getByRole('menuitem', { name: 'Export to PDF' }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: 'Download as Image' }), ).toBeInTheDocument(); });
7,238
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/menu/ShareMenuItems/ShareMenuItems.test.tsx
/** * 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 { Menu } from 'src/components/Menu'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import userEvent from '@testing-library/user-event'; import * as copyTextToClipboard from 'src/utils/copy'; import fetchMock from 'fetch-mock'; import ShareMenuItems from '.'; const spy = jest.spyOn(copyTextToClipboard, 'default'); const DASHBOARD_ID = '26'; const createProps = () => ({ addDangerToast: jest.fn(), addSuccessToast: jest.fn(), url: `/superset/dashboard/${DASHBOARD_ID}`, copyMenuItemTitle: 'Copy dashboard URL', emailMenuItemTitle: 'Share dashboard by email', emailSubject: 'Superset dashboard COVID Vaccine Dashboard', emailBody: 'Check out this dashboard: ', dashboardId: DASHBOARD_ID, }); const { location } = window; beforeAll((): void => { // @ts-ignore delete window.location; fetchMock.post( `http://localhost/api/v1/dashboard/${DASHBOARD_ID}/permalink`, { key: '123', url: 'http://localhost/superset/dashboard/p/123/' }, { sendAsJson: true, }, ); }); beforeEach(() => { jest.clearAllMocks(); window.location = { href: '', } as any; }); afterAll((): void => { window.location = location; }); test('Should render menu items', () => { const props = createProps(); render( <Menu onClick={jest.fn()} selectable={false} data-test="main-menu"> <ShareMenuItems {...props} /> </Menu>, { useRedux: true }, ); expect( screen.getByRole('menuitem', { name: 'Copy dashboard URL' }), ).toBeInTheDocument(); expect( screen.getByRole('menuitem', { name: 'Share dashboard by email' }), ).toBeInTheDocument(); expect( screen.getByRole('button', { name: 'Copy dashboard URL' }), ).toBeInTheDocument(); expect( screen.getByRole('button', { name: 'Share dashboard by email' }), ).toBeInTheDocument(); }); test('Click on "Copy dashboard URL" and succeed', async () => { spy.mockResolvedValue(undefined); const props = createProps(); render( <Menu onClick={jest.fn()} selectable={false} data-test="main-menu"> <ShareMenuItems {...props} /> </Menu>, { useRedux: true }, ); await waitFor(() => { expect(spy).toBeCalledTimes(0); expect(props.addSuccessToast).toBeCalledTimes(0); expect(props.addDangerToast).toBeCalledTimes(0); }); userEvent.click(screen.getByRole('button', { name: 'Copy dashboard URL' })); await waitFor(async () => { expect(spy).toBeCalledTimes(1); const value = await spy.mock.calls[0][0](); expect(value).toBe('http://localhost/superset/dashboard/p/123/'); expect(props.addSuccessToast).toBeCalledTimes(1); expect(props.addSuccessToast).toBeCalledWith('Copied to clipboard!'); expect(props.addDangerToast).toBeCalledTimes(0); }); }); test('Click on "Copy dashboard URL" and fail', async () => { spy.mockRejectedValue(undefined); const props = createProps(); render( <Menu onClick={jest.fn()} selectable={false} data-test="main-menu"> <ShareMenuItems {...props} /> </Menu>, { useRedux: true }, ); await waitFor(() => { expect(spy).toBeCalledTimes(0); expect(props.addSuccessToast).toBeCalledTimes(0); expect(props.addDangerToast).toBeCalledTimes(0); }); userEvent.click(screen.getByRole('button', { name: 'Copy dashboard URL' })); await waitFor(async () => { expect(spy).toBeCalledTimes(1); const value = await spy.mock.calls[0][0](); expect(value).toBe('http://localhost/superset/dashboard/p/123/'); expect(props.addSuccessToast).toBeCalledTimes(0); expect(props.addDangerToast).toBeCalledTimes(1); expect(props.addDangerToast).toBeCalledWith( 'Sorry, something went wrong. Try again later.', ); }); }); test('Click on "Share dashboard by email" and succeed', async () => { const props = createProps(); render( <Menu onClick={jest.fn()} selectable={false} data-test="main-menu"> <ShareMenuItems {...props} /> </Menu>, { useRedux: true }, ); await waitFor(() => { expect(props.addDangerToast).toBeCalledTimes(0); expect(window.location.href).toBe(''); }); userEvent.click( screen.getByRole('button', { name: 'Share dashboard by email' }), ); await waitFor(() => { expect(props.addDangerToast).toBeCalledTimes(0); expect(window.location.href).toBe( 'mailto:?Subject=Superset%20dashboard%20COVID%20Vaccine%20Dashboard%20&Body=Check%20out%20this%20dashboard%3A%20http%3A%2F%2Flocalhost%2Fsuperset%2Fdashboard%2Fp%2F123%2F', ); }); }); test('Click on "Share dashboard by email" and fail', async () => { fetchMock.post( `http://localhost/api/v1/dashboard/${DASHBOARD_ID}/permalink`, { status: 404 }, { overwriteRoutes: true }, ); const props = createProps(); render( <Menu onClick={jest.fn()} selectable={false} data-test="main-menu"> <ShareMenuItems {...props} /> </Menu>, { useRedux: true }, ); await waitFor(() => { expect(props.addDangerToast).toBeCalledTimes(0); expect(window.location.href).toBe(''); }); userEvent.click( screen.getByRole('button', { name: 'Share dashboard by email' }), ); await waitFor(() => { expect(window.location.href).toBe(''); expect(props.addDangerToast).toBeCalledTimes(1); expect(props.addDangerToast).toBeCalledWith( 'Sorry, something went wrong. Try again later.', ); }); });
7,242
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/utils.test.ts
/** * 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 { Behavior, FeatureFlag } from '@superset-ui/core'; import * as uiCore from '@superset-ui/core'; import { DashboardLayout } from 'src/dashboard/types'; import { nativeFilterGate, findTabsWithChartsInScope } from './utils'; let isFeatureEnabledMock: jest.MockInstance<boolean, [feature: FeatureFlag]>; describe('nativeFilterGate', () => { describe('with all feature flags disabled', () => { beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation(() => false); }); afterAll(() => { // @ts-ignore isFeatureEnabledMock.restore(); }); it('should return true for regular chart', () => { expect(nativeFilterGate([])).toEqual(true); }); it('should return true for cross filter chart', () => { expect(nativeFilterGate([Behavior.INTERACTIVE_CHART])).toEqual(true); }); it('should return false for native filter chart with cross filter support', () => { expect( nativeFilterGate([Behavior.NATIVE_FILTER, Behavior.INTERACTIVE_CHART]), ).toEqual(false); }); it('should return false for native filter behavior', () => { expect(nativeFilterGate([Behavior.NATIVE_FILTER])).toEqual(false); }); }); describe('with only native filters feature flag enabled', () => { beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation( (featureFlag: FeatureFlag) => featureFlag === FeatureFlag.DASHBOARD_NATIVE_FILTERS, ); }); afterAll(() => { // @ts-ignore isFeatureEnabledMock.restore(); }); it('should return true for regular chart', () => { expect(nativeFilterGate([])).toEqual(true); }); it('should return true for cross filter chart', () => { expect(nativeFilterGate([Behavior.INTERACTIVE_CHART])).toEqual(true); }); it('should return false for native filter chart with cross filter support', () => { expect( nativeFilterGate([Behavior.NATIVE_FILTER, Behavior.INTERACTIVE_CHART]), ).toEqual(false); }); it('should return false for native filter behavior', () => { expect(nativeFilterGate([Behavior.NATIVE_FILTER])).toEqual(false); }); }); describe('with native filters and experimental feature flag enabled', () => { beforeAll(() => { isFeatureEnabledMock = jest .spyOn(uiCore, 'isFeatureEnabled') .mockImplementation((featureFlag: FeatureFlag) => [ FeatureFlag.DASHBOARD_CROSS_FILTERS, FeatureFlag.DASHBOARD_FILTERS_EXPERIMENTAL, ].includes(featureFlag), ); }); afterAll(() => { // @ts-ignore isFeatureEnabledMock.restore(); }); it('should return true for regular chart', () => { expect(nativeFilterGate([])).toEqual(true); }); it('should return true for cross filter chart', () => { expect(nativeFilterGate([Behavior.INTERACTIVE_CHART])).toEqual(true); }); it('should return true for native filter chart with cross filter support', () => { expect( nativeFilterGate([Behavior.NATIVE_FILTER, Behavior.INTERACTIVE_CHART]), ).toEqual(true); }); it('should return false for native filter behavior', () => { expect(nativeFilterGate([Behavior.NATIVE_FILTER])).toEqual(false); }); }); }); test('findTabsWithChartsInScope should handle a recursive layout structure', () => { const dashboardLayout = { DASHBOARD_VERSION_KEY: 'v2', ROOT_ID: { children: ['GRID_ID'], id: 'ROOT_ID', type: 'ROOT', }, GRID_ID: { children: ['TAB-LrujeuD5Qn', 'TABS-kN7tw6vFif'], id: 'GRID_ID', parents: ['ROOT_ID'], type: 'GRID', }, 'TAB-LrujeuD5Qn': { children: ['TABS-kN7tw6vFif'], id: 'TAB-LrujeuD5Qn', meta: { text: 'View by Totals', }, parents: ['ROOT_ID'], type: 'TAB', }, 'TABS-kN7tw6vFif': { children: ['TAB-LrujeuD5Qn', 'TAB--7BUkKkNl'], id: 'TABS-kN7tw6vFif', meta: {}, parents: ['ROOT_ID'], type: 'TABS', }, } as any as DashboardLayout; expect(Array.from(findTabsWithChartsInScope(dashboardLayout, []))).toEqual( [], ); });
7,244
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/FilterBar.test.tsx
/** * 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 { stateWithoutNativeFilters } from 'spec/fixtures/mockStore'; import * as mockCore from '@superset-ui/core'; import { testWithId } from 'src/utils/testUtils'; import { FeatureFlag, Preset } from '@superset-ui/core'; import { TimeFilterPlugin, SelectFilterPlugin } from 'src/filters/components'; import { DATE_FILTER_TEST_KEY } from 'src/explore/components/controls/DateFilterControl'; import fetchMock from 'fetch-mock'; import { waitFor } from '@testing-library/react'; import { FilterBarOrientation } from 'src/dashboard/types'; import { FILTER_BAR_TEST_ID } from './utils'; import FilterBar from '.'; import { FILTERS_CONFIG_MODAL_TEST_ID } from '../FiltersConfigModal/FiltersConfigModal'; jest.useFakeTimers(); // @ts-ignore mockCore.makeApi = jest.fn(); class MainPreset extends Preset { constructor() { super({ name: 'Legacy charts', plugins: [ new TimeFilterPlugin().configure({ key: 'filter_time' }), new SelectFilterPlugin().configure({ key: 'filter_select' }), ], }); } } fetchMock.get('glob:*/api/v1/dataset/7', { description_columns: {}, id: 1, label_columns: { columns: 'Columns', table_name: 'Table Name', }, result: { metrics: [], columns: [ { column_name: 'Column A', id: 1, }, ], table_name: 'birth_names', id: 1, }, show_columns: ['id', 'table_name'], }); const getTestId = testWithId<string>(FILTER_BAR_TEST_ID, true); const getModalTestId = testWithId<string>(FILTERS_CONFIG_MODAL_TEST_ID, true); const FILTER_NAME = 'Time filter 1'; const FILTER_SET_NAME = 'New filter set'; // @ts-ignore global.featureFlags = { [FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, [FeatureFlag.DASHBOARD_NATIVE_FILTERS_SET]: true, }; const addFilterFlow = async () => { // open filter config modal userEvent.click(screen.getByTestId(getTestId('collapsable'))); userEvent.click(screen.getByTestId(getTestId('create-filter'))); // select filter userEvent.click(screen.getByText('Value')); userEvent.click(screen.getByText('Time range')); userEvent.type(screen.getByTestId(getModalTestId('name-input')), FILTER_NAME); userEvent.click(screen.getByText('Save')); // TODO: fix this flaky test // await screen.findByText('All filters (1)'); }; const addFilterSetFlow = async () => { // add filter set userEvent.click(screen.getByText('Filter sets (0)')); // check description expect(screen.getByText('Filters (1)')).toBeInTheDocument(); expect(screen.getByText(FILTER_NAME)).toBeInTheDocument(); expect(screen.getAllByText('No filter').length).toBe(1); // apply filters expect(screen.getByTestId(getTestId('new-filter-set-button'))).toBeEnabled(); // create filter set userEvent.click(screen.getByText('Create new filter set')); userEvent.click(screen.getByText('Create')); // check filter set created expect(await screen.findByRole('img', { name: 'check' })).toBeInTheDocument(); expect(screen.getByTestId(getTestId('filter-set-wrapper'))).toHaveAttribute( 'data-selected', 'true', ); }; const changeFilterValue = async () => { userEvent.click(screen.getAllByText('No filter')[0]); userEvent.click(screen.getByDisplayValue('Last day')); expect(await screen.findByText(/2021-04-13/)).toBeInTheDocument(); userEvent.click(screen.getByTestId(DATE_FILTER_TEST_KEY.applyButton)); }; describe('FilterBar', () => { new MainPreset().register(); const toggleFiltersBar = jest.fn(); const closedBarProps = { filtersOpen: false, toggleFiltersBar, }; const openedBarProps = { filtersOpen: true, toggleFiltersBar, }; const mockApi = jest.fn(async data => { const json = JSON.parse(data.json_metadata); const filterId = json.native_filter_configuration[0].id; return { id: 1234, result: { json_metadata: `{ "label_colors":{"Girls":"#FF69B4","Boys":"#ADD8E6","girl":"#FF69B4","boy":"#ADD8E6"}, "native_filter_configuration":[{ "id":"${filterId}", "name":"${FILTER_NAME}", "filterType":"filter_time", "targets":[{"datasetId":11,"column":{"name":"color"}}], "defaultDataMask":{"filterState":{"value":null}}, "controlValues":{}, "cascadeParentIds":[], "scope":{"rootPath":["ROOT_ID"],"excluded":[]} }], "filter_sets_configuration":[{ "name":"${FILTER_SET_NAME}", "id":"${json.filter_sets_configuration?.[0].id}", "nativeFilters":{ "${filterId}":{ "id":"${filterId}", "name":"${FILTER_NAME}", "filterType":"filter_time", "targets":[{}], "defaultDataMask":{"filterState":{},"extraFormData":{}}, "controlValues":{}, "cascadeParentIds":[], "scope":{"rootPath":["ROOT_ID"],"excluded":[]} } }, "dataMask":{ "${filterId}":{ "extraFormData":{}, "filterState":{}, "ownState":{}, "id":"${filterId}" } } }] }`, }, }; }); beforeEach(() => { jest.clearAllMocks(); fetchMock.get( 'glob:*/api/v1/time_range/?q=%27No%20filter%27', { result: { since: '', until: '', timeRange: 'No filter' }, }, { overwriteRoutes: true }, ); fetchMock.get( 'glob:*/api/v1/time_range/?q=%27Last%20day%27', { result: { since: '2021-04-13T00:00:00', until: '2021-04-14T00:00:00', timeRange: 'Last day', }, }, { overwriteRoutes: true }, ); fetchMock.get( 'glob:*/api/v1/time_range/?q=%27Last%20week%27', { result: { since: '2021-04-07T00:00:00', until: '2021-04-14T00:00:00', timeRange: 'Last week', }, }, { overwriteRoutes: true }, ); // @ts-ignore mockCore.makeApi = jest.fn(() => mockApi); }); const renderWrapper = (props = closedBarProps, state?: object) => render( <FilterBar orientation={FilterBarOrientation.VERTICAL} verticalConfig={{ width: 280, height: 400, offset: 0, ...props, }} />, { initialState: state, useDnd: true, useRedux: true, useRouter: true, }, ); it('should render', () => { const { container } = renderWrapper(); expect(container).toBeInTheDocument(); }); it('should render the "Filters" heading', () => { renderWrapper(); expect(screen.getByText('Filters')).toBeInTheDocument(); }); it('should render the "Clear all" option', () => { renderWrapper(); expect(screen.getByText('Clear all')).toBeInTheDocument(); }); it('should render the "Apply filters" option', () => { renderWrapper(); expect(screen.getByText('Apply filters')).toBeInTheDocument(); }); it('should render the collapse icon', () => { renderWrapper(); expect(screen.getByRole('img', { name: 'collapse' })).toBeInTheDocument(); }); it('should render the filter icon', () => { renderWrapper(); expect(screen.getByRole('img', { name: 'filter' })).toBeInTheDocument(); }); it('should toggle', () => { renderWrapper(); const collapse = screen.getByRole('img', { name: 'collapse' }); expect(toggleFiltersBar).not.toHaveBeenCalled(); userEvent.click(collapse); expect(toggleFiltersBar).toHaveBeenCalled(); }); it('open filter bar', () => { renderWrapper(); expect(screen.getByTestId(getTestId('filter-icon'))).toBeInTheDocument(); expect(screen.getByTestId(getTestId('expand-button'))).toBeInTheDocument(); userEvent.click(screen.getByTestId(getTestId('collapsable'))); expect(toggleFiltersBar).toHaveBeenCalledWith(true); }); it('no edit filter button by disabled permissions', () => { renderWrapper(openedBarProps, { ...stateWithoutNativeFilters, dashboardInfo: { metadata: {} }, }); expect( screen.queryByTestId(getTestId('create-filter')), ).not.toBeInTheDocument(); }); it('close filter bar', () => { renderWrapper(openedBarProps); const collapseButton = screen.getByTestId(getTestId('collapse-button')); expect(collapseButton).toBeInTheDocument(); userEvent.click(collapseButton); expect(toggleFiltersBar).toHaveBeenCalledWith(false); }); it('no filters', () => { renderWrapper(openedBarProps, stateWithoutNativeFilters); expect(screen.getByTestId(getTestId('clear-button'))).toBeDisabled(); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); }); it('renders dividers', async () => { const divider = { id: 'NATIVE_FILTER_DIVIDER-1', type: 'DIVIDER', scope: { rootPath: ['ROOT_ID'], excluded: [], }, title: 'Select time range', description: 'Select year/month etc..', chartsInScope: [], tabsInScope: [], }; const stateWithDivider = { ...stateWithoutNativeFilters, nativeFilters: { filters: { 'NATIVE_FILTER_DIVIDER-1': divider, }, }, }; renderWrapper(openedBarProps, stateWithDivider); const title = await screen.findByText('Select time range'); const description = await screen.findByText('Select year/month etc..'); expect(title.tagName).toBe('H3'); expect(description.tagName).toBe('P'); // Do not enable buttons if there are not filters expect(screen.getByTestId(getTestId('clear-button'))).toBeDisabled(); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); }); it('create filter and apply it flow', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.DASHBOARD_NATIVE_FILTERS_SET]: true, [FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, }; renderWrapper(openedBarProps, stateWithoutNativeFilters); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); await addFilterFlow(); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); }); // disable due to filter sets not detecting changes in metadata properly it.skip('add and apply filter set', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, [FeatureFlag.DASHBOARD_NATIVE_FILTERS_SET]: true, }; renderWrapper(openedBarProps, stateWithoutNativeFilters); await addFilterFlow(); userEvent.click(screen.getByTestId(getTestId('apply-button'))); await addFilterSetFlow(); // change filter expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); userEvent.click(await screen.findByText('All filters (1)')); await changeFilterValue(); await waitFor(() => expect(screen.getAllByText('Last day').length).toBe(2)); // apply new filter value userEvent.click(screen.getByTestId(getTestId('apply-button'))); await waitFor(() => expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(), ); // applying filter set userEvent.click(screen.getByText('Filter Sets (1)')); expect( await screen.findByText('Create new filter set'), ).toBeInTheDocument(); expect( screen.getByTestId(getTestId('filter-set-wrapper')), ).not.toHaveAttribute('data-selected', 'true'); userEvent.click(screen.getByTestId(getTestId('filter-set-wrapper'))); userEvent.click(screen.getAllByText('Filters (1)')[1]); expect(await screen.findByText('No filter')).toBeInTheDocument(); userEvent.click(screen.getByTestId(getTestId('apply-button'))); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); }); // disable due to filter sets not detecting changes in metadata properly it.skip('add and edit filter set', async () => { // @ts-ignore global.featureFlags = { [FeatureFlag.DASHBOARD_NATIVE_FILTERS_SET]: true, [FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, }; renderWrapper(openedBarProps, stateWithoutNativeFilters); await addFilterFlow(); userEvent.click(screen.getByTestId(getTestId('apply-button'))); await addFilterSetFlow(); userEvent.click(screen.getByTestId(getTestId('filter-set-menu-button'))); userEvent.click(screen.getByText('Edit')); await changeFilterValue(); // apply new changes and save them await waitFor(() => expect( screen.getByTestId(getTestId('filter-set-edit-save')), ).toBeDisabled(), ); expect(screen.getByTestId(getTestId('apply-button'))).toBeEnabled(); userEvent.click(screen.getByTestId(getTestId('apply-button'))); expect(screen.getByTestId(getTestId('apply-button'))).toBeDisabled(); expect(screen.getByTestId(getTestId('filter-set-edit-save'))).toBeEnabled(); userEvent.click(screen.getByTestId(getTestId('filter-set-edit-save'))); expect(screen.queryByText('Save')).not.toBeInTheDocument(); expect( Object.values( JSON.parse(mockApi.mock.calls[2][0].json_metadata) .filter_sets_configuration[0].dataMask as object, )[0]?.filterState?.value, ).toBe('Last day'); }); });
7,246
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/HorizontalFilterBar.test.tsx
/** * 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 { FeatureFlag, NativeFilterType } from '@superset-ui/core'; import React from 'react'; import { render, screen, waitFor } from 'spec/helpers/testing-library'; import HorizontalBar from './Horizontal'; const defaultProps = { actions: null, canEdit: true, dashboardId: 1, dataMaskSelected: {}, filterValues: [], isInitialized: true, onSelectionChange: jest.fn(), }; // @ts-ignore global.featureFlags = { [FeatureFlag.DASHBOARD_NATIVE_FILTERS]: true, }; const renderWrapper = (overrideProps?: Record<string, any>) => waitFor(() => render(<HorizontalBar {...defaultProps} {...overrideProps} />, { useRedux: true, initialState: { dashboardInfo: { dash_edit_perm: true, }, }, }), ); test('should render', async () => { const { container } = await renderWrapper(); expect(container).toBeInTheDocument(); }); test('should not render the empty message', async () => { await renderWrapper({ filterValues: [ { id: 'test', type: NativeFilterType.NATIVE_FILTER, }, ], }); expect( screen.queryByText('No filters are currently added to this dashboard.'), ).not.toBeInTheDocument(); }); test('should render the empty message', async () => { await renderWrapper(); expect( screen.getByText('No filters are currently added to this dashboard.'), ).toBeInTheDocument(); }); test('should not render the loading icon', async () => { await renderWrapper(); expect( screen.queryByRole('status', { name: 'Loading' }), ).not.toBeInTheDocument(); }); test('should render the loading icon', async () => { await renderWrapper({ isInitialized: false, }); expect(screen.getByRole('status', { name: 'Loading' })).toBeInTheDocument(); }); test('should render Add/Edit Filters', async () => { await renderWrapper(); expect(screen.getByText('Add/Edit Filters')).toBeInTheDocument(); }); test('should not render Add/Edit Filters', async () => { await renderWrapper({ canEdit: false, }); expect(screen.queryByText('Add/Edit Filters')).not.toBeInTheDocument(); });
7,255
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/ActionButtons/ActionButtons.test.tsx
/** * 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 { OPEN_FILTER_BAR_WIDTH } from 'src/dashboard/constants'; import userEvent from '@testing-library/user-event'; import { render, screen } from 'spec/helpers/testing-library'; import ActionButtons from './index'; const createProps = () => ({ onApply: jest.fn(), onClearAll: jest.fn(), dataMaskSelected: { DefaultsID: { filterState: { value: null, }, }, }, dataMaskApplied: { DefaultsID: { id: 'DefaultsID', filterState: { value: null, }, }, }, isApplyDisabled: false, }); test('should render the "Apply" button', () => { const mockedProps = createProps(); render(<ActionButtons {...mockedProps} />, { useRedux: true }); expect(screen.getByText('Apply filters')).toBeInTheDocument(); expect(screen.getByText('Apply filters').parentElement).toBeEnabled(); }); test('should render the "Clear all" button as disabled', () => { const mockedProps = createProps(); render(<ActionButtons {...mockedProps} />, { useRedux: true }); const clearBtn = screen.getByText('Clear all'); expect(clearBtn.parentElement).toBeDisabled(); }); test('should render the "Apply" button as disabled', () => { const mockedProps = createProps(); const applyDisabledProps = { ...mockedProps, isApplyDisabled: true, }; render(<ActionButtons {...applyDisabledProps} />, { useRedux: true }); const applyBtn = screen.getByText('Apply filters'); expect(applyBtn.parentElement).toBeDisabled(); userEvent.click(applyBtn); expect(mockedProps.onApply).not.toHaveBeenCalled(); }); test('should apply', () => { const mockedProps = createProps(); render(<ActionButtons {...mockedProps} />, { useRedux: true }); const applyBtn = screen.getByText('Apply filters'); expect(mockedProps.onApply).not.toHaveBeenCalled(); userEvent.click(applyBtn); expect(mockedProps.onApply).toHaveBeenCalled(); }); describe('custom width', () => { it('sets its default width with OPEN_FILTER_BAR_WIDTH', () => { const mockedProps = createProps(); render(<ActionButtons {...mockedProps} />, { useRedux: true }); const container = screen.getByTestId('filterbar-action-buttons'); expect(container).toHaveStyleRule( 'width', `${OPEN_FILTER_BAR_WIDTH - 1}px`, ); }); it('sets custom width', () => { const mockedProps = createProps(); const expectedWidth = 423; const { getByTestId } = render( <ActionButtons {...mockedProps} width={expectedWidth} />, { useRedux: true, }, ); const container = getByTestId('filterbar-action-buttons'); expect(container).toHaveStyleRule('width', `${expectedWidth - 1}px`); }); });
7,257
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/CrossFilter.test.tsx
/** * 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 { FilterBarOrientation } from 'src/dashboard/types'; import { IndicatorStatus } from '../../selectors'; import CrossFilter from './CrossFilter'; const mockedProps = { filter: { name: 'test', emitterId: 1, column: 'country_name', value: 'Italy', status: IndicatorStatus.CrossFilterApplied, path: ['test-path'], }, orientation: FilterBarOrientation.HORIZONTAL, last: false, }; const setup = (props: typeof mockedProps) => render(<CrossFilter {...props} />, { useRedux: true, }); test('CrossFilter should render', () => { const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('Title should render', () => { setup(mockedProps); expect(screen.getByText('test')).toBeInTheDocument(); }); test('Search icon should be visible', () => { setup(mockedProps); expect( screen.getByTestId('cross-filters-highlight-emitter'), ).toBeInTheDocument(); }); test('Column and value should be visible', () => { setup(mockedProps); expect(screen.getByText('country_name')).toBeInTheDocument(); expect(screen.getByText('Italy')).toBeInTheDocument(); }); test('Tag should be closable', () => { setup(mockedProps); expect(screen.getByRole('img', { name: 'close' })).toBeInTheDocument(); }); test('Divider should not be visible', () => { setup(mockedProps); expect(screen.queryByTestId('cross-filters-divider')).not.toBeInTheDocument(); }); test('Divider should be visible', () => { setup({ ...mockedProps, last: true, }); expect(screen.getByTestId('cross-filters-divider')).toBeInTheDocument(); });
7,259
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/CrossFilterTag.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { FilterBarOrientation } from 'src/dashboard/types'; import { CrossFilterIndicator, IndicatorStatus } from '../../selectors'; import CrossFilterTag from './CrossFilterTag'; const mockedProps: { filter: CrossFilterIndicator; orientation: FilterBarOrientation; removeCrossFilter: (filterId: number) => void; } = { filter: { name: 'test', emitterId: 1, column: 'country_name', value: 'Italy', status: IndicatorStatus.CrossFilterApplied, path: ['test-path'], }, orientation: FilterBarOrientation.HORIZONTAL, removeCrossFilter: jest.fn(), }; const setup = (props: typeof mockedProps) => render(<CrossFilterTag {...props} />, { useRedux: true, }); test('CrossFilterTag should render', () => { const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('CrossFilterTag with adhoc column should render', () => { const props = { ...mockedProps, filter: { ...mockedProps.filter, column: { label: 'My column', sqlExpression: 'country_name', expressionType: 'SQL' as const, }, }, }; const { container } = setup(props); expect(container).toBeInTheDocument(); expect(screen.getByText('My column')).toBeInTheDocument(); expect(screen.getByText('Italy')).toBeInTheDocument(); }); test('Column and value should be visible', () => { setup(mockedProps); expect(screen.getByText('country_name')).toBeInTheDocument(); expect(screen.getByText('Italy')).toBeInTheDocument(); }); test('Tag should be closable', () => { setup(mockedProps); const close = screen.getByRole('img', { name: 'close' }); expect(close).toBeInTheDocument(); userEvent.click(close); expect(mockedProps.removeCrossFilter).toHaveBeenCalledWith(1); });
7,261
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/CrossFilterTitle.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import React from 'react'; import { render, screen } from 'spec/helpers/testing-library'; import { FilterBarOrientation } from 'src/dashboard/types'; import CrossFilterTitle from './CrossFilterTitle'; const mockedProps = { title: 'test-title', orientation: FilterBarOrientation.HORIZONTAL, onHighlightFilterSource: jest.fn(), }; const setup = (props: typeof mockedProps) => render(<CrossFilterTitle {...props} />, { useRedux: true, }); test('CrossFilterTitle should render', () => { const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('Title should be visible', () => { setup(mockedProps); expect(screen.getByText('test-title')).toBeInTheDocument(); }); test('Search icon should highlight emitter', () => { setup(mockedProps); const search = screen.getByTestId('cross-filters-highlight-emitter'); expect(search).toBeInTheDocument(); userEvent.click(search); expect(mockedProps.onHighlightFilterSource).toHaveBeenCalled(); });
7,264
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/VerticalCollapse.test.tsx
/** * 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 { IndicatorStatus } from '../../selectors'; import VerticalCollapse from './VerticalCollapse'; const mockedProps = { crossFilters: [ { name: 'test', emitterId: 1, column: 'country_name', value: 'Italy', status: IndicatorStatus.CrossFilterApplied, path: ['test-path'], }, { name: 'test-b', emitterId: 2, column: 'country_code', value: 'IT', status: IndicatorStatus.CrossFilterApplied, path: ['test-path-2'], }, ], }; const setup = (props: typeof mockedProps) => render(<VerticalCollapse {...props} />, { useRedux: true, }); test('VerticalCollapse should render', () => { const { container } = setup(mockedProps); expect(container).toBeInTheDocument(); }); test('Collapse with title should render', () => { setup(mockedProps); expect(screen.getByText('Cross-filters')).toBeInTheDocument(); }); test('Collapse should not render when empty', () => { setup({ crossFilters: [], }); expect(screen.queryByText('Cross-filters')).not.toBeInTheDocument(); expect(screen.queryByText('test')).not.toBeInTheDocument(); expect(screen.queryByText('test-b')).not.toBeInTheDocument(); expect( screen.queryByTestId('cross-filters-highlight-emitter'), ).not.toBeInTheDocument(); expect(screen.queryByRole('img', { name: 'close' })).not.toBeInTheDocument(); expect(screen.queryByText('country_name')).not.toBeInTheDocument(); expect(screen.queryByText('Italy')).not.toBeInTheDocument(); expect(screen.queryByText('country_code')).not.toBeInTheDocument(); expect(screen.queryByText('IT')).not.toBeInTheDocument(); expect(screen.queryByTestId('cross-filters-divider')).not.toBeInTheDocument(); }); test('Titles should be visible', () => { setup(mockedProps); expect(screen.getByText('test')).toBeInTheDocument(); expect(screen.getByText('test-b')).toBeInTheDocument(); }); test('Search icons should be visible', () => { setup(mockedProps); expect(screen.getAllByTestId('cross-filters-highlight-emitter')).toHaveLength( 2, ); }); test('Tags should be visible', () => { setup(mockedProps); expect(screen.getByText('country_name')).toBeInTheDocument(); expect(screen.getByText('Italy')).toBeInTheDocument(); expect(screen.getByText('country_code')).toBeInTheDocument(); expect(screen.getByText('IT')).toBeInTheDocument(); }); test('Tags should be closable', () => { setup(mockedProps); expect(screen.getAllByRole('img', { name: 'close' })).toHaveLength(2); }); test('Divider should be visible', () => { setup(mockedProps); expect(screen.getByTestId('cross-filters-divider')).toBeInTheDocument(); });
7,268
0
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters
petrpan-code/apache/superset/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/ScopingModal/ChartsScopingListPanel.test.tsx
/** * 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 userEvent from '@testing-library/user-event'; import { render, screen, within } from 'spec/helpers/testing-library'; import { CHART_TYPE } from 'src/dashboard/util/componentTypes'; import { ChartsScopingListPanel, ChartsScopingListPanelProps, } from './ChartsScopingListPanel'; const DEFAULT_PROPS: ChartsScopingListPanelProps = { addNewCustomScope: jest.fn(), removeCustomScope: jest.fn(), setCurrentChartId: jest.fn(), activeChartId: undefined, chartConfigs: { 1: { id: 1, crossFilters: { scope: 'global' as const, chartsInScope: [2, 3, 4], }, }, 2: { id: 2, crossFilters: { scope: 'global' as const, chartsInScope: [1, 3, 4], }, }, 3: { id: 3, crossFilters: { scope: { rootPath: ['ROOT_ID'], excluded: [1, 3], }, chartsInScope: [2, 4], }, }, 4: { id: 4, crossFilters: { scope: { rootPath: ['ROOT_ID'], excluded: [1, 4], }, chartsInScope: [2, 3], }, }, }, }; const INITIAL_STATE = { dashboardLayout: { past: [], future: [], present: { CHART_1: { id: 'CHART_1', type: CHART_TYPE, meta: { chartId: 1, sliceName: 'chart 1', }, }, CHART_2: { id: 'CHART_2', type: CHART_TYPE, meta: { chartId: 2, sliceName: 'chart 2', }, }, CHART_3: { id: 'CHART_3', type: CHART_TYPE, meta: { chartId: 3, sliceName: 'chart 3', sliceNameOverride: 'Chart 3', }, }, CHART_4: { id: 'CHART_4', type: CHART_TYPE, meta: { chartId: 4, sliceName: 'chart 4', }, }, }, }, }; const setup = (props = DEFAULT_PROPS) => render(<ChartsScopingListPanel {...props} />, { useRedux: true, initialState: INITIAL_STATE, }); it('Renders charts scoping list panel', () => { setup(); expect(screen.getByText('Add custom scoping')).toBeVisible(); expect(screen.getByText('All charts/global scoping')).toBeVisible(); expect(screen.getByText('All charts/global scoping')).toHaveClass('active'); expect(screen.queryByText('chart 1')).not.toBeInTheDocument(); expect(screen.queryByText('chart 2')).not.toBeInTheDocument(); expect(screen.getByText('Chart 3')).toBeVisible(); expect(screen.getByText('chart 4')).toBeVisible(); expect(screen.queryByText('[new custom scoping]')).not.toBeInTheDocument(); }); it('Renders custom scoping item', () => { setup({ ...DEFAULT_PROPS, activeChartId: -1, chartConfigs: { ...DEFAULT_PROPS.chartConfigs, [-1]: { id: -1, crossFilters: { scope: 'global', chartsInScope: [1, 2, 3, 4], }, }, }, }); expect(screen.getByText('All charts/global scoping')).toBeVisible(); expect(screen.getByText('All charts/global scoping')).not.toHaveClass( 'active', ); expect(screen.queryByText('chart 1')).not.toBeInTheDocument(); expect(screen.queryByText('chart 2')).not.toBeInTheDocument(); expect(screen.getByText('Chart 3')).toBeVisible(); expect(screen.getByText('chart 4')).toBeVisible(); expect(screen.getByText('[new custom scoping]')).toBeVisible(); expect(screen.getByText('[new custom scoping]')).toHaveClass('active'); }); it('Uses callbacks on click', () => { setup(); userEvent.click(screen.getByText('Add custom scoping')); expect(DEFAULT_PROPS.addNewCustomScope).toHaveBeenCalled(); userEvent.click(screen.getByText('All charts/global scoping')); expect(DEFAULT_PROPS.setCurrentChartId).toHaveBeenCalledWith(undefined); userEvent.click(screen.getByText('Chart 3')); expect(DEFAULT_PROPS.setCurrentChartId).toHaveBeenCalledWith(3); const chart4Container = screen.getByText('chart 4').closest('div'); if (chart4Container) { userEvent.click(within(chart4Container).getByLabelText('trash')); } expect(DEFAULT_PROPS.removeCustomScope).toHaveBeenCalledWith(4); });