Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[Security Solution] Fixing jest warnings and errors #86532

Merged
merged 7 commits into from
Dec 21, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,17 @@ const CaseActionBarComponent: React.FC<CaseActionBarProps> = ({
<EuiDescriptionList compressed>
<EuiFlexGroup gutterSize="l" alignItems="center">
<EuiFlexItem>
<EuiDescriptionListTitle>
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This clears up the following error that showed in cases/components/case_view/index.test.tsx

Warning: validateDOMNesting(...): <dt> cannot appear as a descendant of <dd>.
  in dt (created by EuiDescriptionListTitle)
  in EuiDescriptionListTitle (created by CaseActionBarComponent)
  in dd (created by EuiDescriptionListDescription)
  in EuiDescriptionListDescription (created by CaseActionBarComponent)
  in div (created by EuiFlexItem)

<EuiFlexGroup component="span" alignItems="center" gutterSize="xs">
<EuiFlexItem grow={false}>
<span>{i18n.SYNC_ALERTS}</span>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiIconTip content={i18n.SYNC_ALERTS_HELP} />
</EuiFlexItem>
</EuiFlexGroup>
</EuiDescriptionListTitle>
<EuiDescriptionListDescription>
<EuiDescriptionListTitle>
<EuiFlexGroup component="span" alignItems="center" gutterSize="xs">
<EuiFlexItem grow={false}>
<span>{i18n.SYNC_ALERTS}</span>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiIconTip content={i18n.SYNC_ALERTS_HELP} />
</EuiFlexItem>
</EuiFlexGroup>
</EuiDescriptionListTitle>
<SyncAlertsSwitch
disabled={disabled || isLoading}
isSynced={caseData.settings.syncAlerts}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { shallow } from 'enzyme';
import { ReactWrapper, shallow } from 'enzyme';
import React from 'react';

import '../../mock/match_media';
Expand All @@ -16,6 +16,7 @@ import { mockBrowserFields } from '../../containers/source/mock';
import { useMountAppended } from '../../utils/use_mount_appended';
import { mockAlertDetailsData } from './__mocks__';
import { TimelineEventsDetailsItem } from '../../../../common/search_strategy';
import { waitFor } from '@testing-library/dom';

jest.mock('../link_to');
describe('EventDetails', () => {
Expand All @@ -36,18 +37,21 @@ describe('EventDetails', () => {
isAlert: true,
};

const wrapper = mount(
<TestProviders>
<EventDetails {...defaultProps} />
</TestProviders>
);

const alertsWrapper = mount(
<TestProviders>
<EventDetails {...alertsProps} />
</TestProviders>
);

let wrapper: ReactWrapper;
let alertsWrapper: ReactWrapper;
beforeAll(async () => {
wrapper = mount(
<TestProviders>
<EventDetails {...defaultProps} />
</TestProviders>
) as ReactWrapper;
alertsWrapper = mount(
<TestProviders>
<EventDetails {...alertsProps} />
</TestProviders>
) as ReactWrapper;
await waitFor(() => wrapper.update());
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following error:

    Warning: An update to SummaryViewComponent inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
        in SummaryViewComponent (created by EventDetailsComponent)
        in div (created by EuiTabbedContent)
        in div (created by EuiTabbedContent)
        in EuiTabbedContent (created by Styled(EuiTabbedContent))
        in Styled(EuiTabbedContent) (created by EventDetailsComponent)
        in EventDetailsComponent

});
describe('rendering', () => {
test('should match snapshot', () => {
const shallowWrap = shallow(<EventDetails {...defaultProps} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ jest.mock('../../../timelines/components/graph_overlay', () => ({
GraphOverlay: jest.fn(() => <div />),
}));

jest.mock('@elastic/eui', () => {
const original = jest.requireActual('@elastic/eui');
return {
...original,
useDataGridColumnSorting: jest.fn(),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following error:

    Warning: Failed prop type: The prop `display` is marked as required in `EuiDataGridColumnSortingDraggable`, but its value is `undefined`.
        in EuiDataGridColumnSortingDraggable (created by ColumnHeadersComponent)
        in ColumnHeadersComponent
        in ColumnHeadersComponent
        in div (created by styled.div)
        in styled.div
        in div (created by TimelineBody)
        in TimelineBody

};
});
jest.mock('../../../timelines/containers', () => ({
useTimelineEvents: jest.fn(),
}));
Expand Down Expand Up @@ -84,7 +91,7 @@ const eventsViewerDefaultProps = {
sort: [
{
columnId: 'foo',
sortDirection: 'none' as SortDirection,
sortDirection: 'asc' as SortDirection,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following error:

    Warning: Failed prop type: Invalid prop `sorting.columns[0].direction` of value `none` supplied to `EuiDataGridColumnSortingDraggable`, expected one of ["asc","desc"].
        in EuiDataGridColumnSortingDraggable (created by ColumnHeadersComponent)
        in ColumnHeadersComponent
        in ColumnHeadersComponent
        in div (created by styled.div)
        in styled.div
        in div (created by TimelineBody)
        in TimelineBody

},
],
scopeId: SourcererScopeName.timeline,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from '../../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks';
import { getFoundListSchemaMock } from '../../../../../../lists/common/schemas/response/found_list_schema.mock';
import { getEmptyValue } from '../../empty_value';
import { waitFor } from '@testing-library/dom';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

the waitFors clear up a couple of these errors:

    Warning: An update to AutocompleteFieldMatchAny inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
        in AutocompleteFieldMatchAny (created by BuilderEntryItem)
        in div (created by EuiFlexItem)


// mock out lists hook
const mockStart = jest.fn();
Expand Down Expand Up @@ -583,7 +584,7 @@ describe('BuilderEntryItem', () => {
);
});

test('it invokes "setErrorsExist" when user touches value input and leaves empty', () => {
test('it invokes "setErrorsExist" when user touches value input and leaves empty', async () => {
const mockSetErrorExists = jest.fn();
wrapper = mount(
<BuilderEntryItem
Expand All @@ -608,14 +609,16 @@ describe('BuilderEntryItem', () => {
/>
);

((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onBlur: () => void;
}).onBlur();
await waitFor(() => {
((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onBlur: () => void;
}).onBlur();
});

expect(mockSetErrorExists).toHaveBeenCalledWith(true);
});

test('it invokes "setErrorsExist" when invalid value inputted for field value input', () => {
test('it invokes "setErrorsExist" when invalid value inputted for field value input', async () => {
const mockSetErrorExists = jest.fn();
wrapper = mount(
<BuilderEntryItem
Expand All @@ -639,14 +642,17 @@ describe('BuilderEntryItem', () => {
setErrorsExist={mockSetErrorExists}
/>
);
((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onBlur: () => void;
}).onBlur();

// Invalid input because field type is number
((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onSearchChange: (arg: string) => void;
}).onSearchChange('hellooo');
await waitFor(() => {
((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onBlur: () => void;
}).onBlur();

// Invalid input because field type is number
((wrapper.find(EuiComboBox).at(2).props() as unknown) as {
onSearchChange: (arg: string) => void;
}).onSearchChange('hellooo');
});

expect(mockSetErrorExists).toHaveBeenCalledWith(true);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,18 @@ import { mount } from 'enzyme';
import { I18nProvider } from '@kbn/i18n/react';

import { LastUpdatedAt } from './';
jest.mock('@kbn/i18n/react', () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following warning:

  console.warn
    Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

    * Move data fetching code or side effects to componentDidUpdate.
    * If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
    * Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

    Please update the following components: FormattedRelative

const originalModule = jest.requireActual('@kbn/i18n/react');
const FormattedRelative = jest.fn();
FormattedRelative.mockImplementation(() => '2 minutes ago');

return {
...originalModule,
FormattedRelative,
};
});

describe('LastUpdatedAt', () => {
beforeEach(() => {
Date.now = jest.fn().mockReturnValue(1603995369774);
});

test('it renders correct relative time', () => {
const wrapper = mount(
<I18nProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { mockAnomalies } from '../mock';
import { TestProviders } from '../../../mock/test_providers';
import { useMountAppended } from '../../../utils/use_mount_appended';
import { Anomalies } from '../types';
import { waitFor } from '@testing-library/dom';

const startDate: string = '2020-07-07T08:20:18.966Z';
const endDate: string = '3000-01-01T00:00:00.000Z';
Expand Down Expand Up @@ -57,7 +58,7 @@ describe('anomaly_scores', () => {
expect(wrapper.find('[data-test-subj="anomaly-description-list"]').exists()).toEqual(false);
});

test('show a popover on a mouse click', () => {
test('show a popover on a mouse click', async () => {
const wrapper = mount(
<TestProviders>
<AnomalyScoreComponent
Expand All @@ -71,7 +72,7 @@ describe('anomaly_scores', () => {
</TestProviders>
);
wrapper.find('[data-test-subj="anomaly-score-popover"]').first().simulate('click');
wrapper.update();
await waitFor(() => wrapper.update());
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following warning:

    console.error
      Warning: An update to ExplorerLink inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
          in ExplorerLink (created by AnomalyScoreComponent)
          in div (created by EuiFlexItem)
          in EuiFlexItem (created by AnomalyScoreComponent)
          in div (created by EuiFlexGroup)
          in EuiFlexGroup (created by AnomalyScoreComponent)

expect(wrapper.find('[data-test-subj="anomaly-description-list"]').exists()).toEqual(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { TestProviders } from '../../../mock/test_providers';
import { getEmptyValue } from '../../empty_value';
import { Anomalies } from '../types';
import { useMountAppended } from '../../../utils/use_mount_appended';
import { waitFor } from '@testing-library/dom';

const startDate: string = '2020-07-07T08:20:18.966Z';
const endDate: string = '3000-01-01T00:00:00.000Z';
Expand Down Expand Up @@ -121,7 +122,7 @@ describe('anomaly_scores', () => {
expect(wrapper.find('[data-test-subj="anomaly-description-list"]').exists()).toEqual(false);
});

test('showing a popover on a mouse click', () => {
test('showing a popover on a mouse click', async () => {
const wrapper = mount(
<TestProviders>
<AnomalyScoresComponent
Expand All @@ -134,7 +135,7 @@ describe('anomaly_scores', () => {
</TestProviders>
);
wrapper.find('[data-test-subj="anomaly-score-popover"]').first().simulate('click');
wrapper.update();
await waitFor(() => wrapper.update());
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears up the following warning:

Warning: An update to ExplorerLink inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
          in ExplorerLink (created by AnomalyScoreComponent)
          in div (created by EuiFlexItem)
          in EuiFlexItem (created by AnomalyScoreComponent)
          in div (created by EuiFlexGroup)
          in EuiFlexGroup (created by AnomalyScoreComponent)

expect(wrapper.find('[data-test-subj="anomaly-description-list"]').exists()).toEqual(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { mockAnomalies } from '../mock';
import { createDescriptionList } from './create_description_list';
import { EuiDescriptionList } from '@elastic/eui';
import { Anomaly } from '../types';
import { waitFor } from '@testing-library/dom';
Copy link
Contributor Author

@stephmilovic stephmilovic Dec 18, 2020

Choose a reason for hiding this comment

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

Clears up the following error:

    Warning: An update to ExplorerLink inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
        in ExplorerLink
        in div (created by EuiFlexItem)
        in EuiFlexItem
        in div (created by EuiFlexGroup)
        in EuiFlexGroup
        in dd (created by EuiDescriptionListDescription)
        in EuiDescriptionListDescription (created by EuiDescriptionList)
        in dl (created by EuiDescriptionList)
        in EuiDescriptionList (created by WrapperComponent)


jest.mock('../../../lib/kibana');

Expand Down Expand Up @@ -38,7 +39,7 @@ describe('create_description_list', () => {
expect(wrapper).toMatchSnapshot();
});

test('it calls the narrow date range function on click', () => {
test('it calls the narrow date range function on click', async () => {
const wrapper = mount(
<EuiDescriptionList
listItems={createDescriptionList(
Expand All @@ -54,12 +55,12 @@ describe('create_description_list', () => {
.find('[data-test-subj="anomaly-description-narrow-range-link"]')
.first()
.simulate('click');
wrapper.update();
await waitFor(() => wrapper.update());

expect(narrowDateRange.mock.calls.length).toBe(1);
});

test('it should the narrow date range with the score', () => {
test('it should the narrow date range with the score', async () => {
const wrapper = mount(
<EuiDescriptionList
listItems={createDescriptionList(
Expand All @@ -75,7 +76,7 @@ describe('create_description_list', () => {
.find('[data-test-subj="anomaly-description-narrow-range-link"]')
.first()
.simulate('click');
wrapper.update();
await waitFor(() => wrapper.update());

const expected: Anomaly = {
detectorIndex: 0,
Expand Down Expand Up @@ -119,7 +120,7 @@ describe('create_description_list', () => {
expect(narrowDateRange.mock.calls[0][0]).toEqual(expected);
});

test('it should call the narrow date range with the interval', () => {
test('it should call the narrow date range with the interval', async () => {
const wrapper = mount(
<EuiDescriptionList
listItems={createDescriptionList(
Expand All @@ -135,8 +136,7 @@ describe('create_description_list', () => {
.find('[data-test-subj="anomaly-description-narrow-range-link"]')
.first()
.simulate('click');
wrapper.update();

await waitFor(() => wrapper.update());
expect(narrowDateRange.mock.calls[0][1]).toEqual('hours');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,13 @@ export const useCreateTimelineButton = ({ timelineId, timelineType, closeGearMen
};
const dataTestSubjPrefix =
timelineType === TimelineType.template ? `template-timeline-new` : `timeline-new`;

const { fill: noThanks, ...propsWithoutFill } = buttonProps;
return outline ? (
<EuiButton data-test-subj={`${dataTestSubjPrefix}-with-border`} {...buttonProps}>
{title}
</EuiButton>
) : (
<EuiButtonEmpty data-test-subj={dataTestSubjPrefix} color="text" {...buttonProps}>
<EuiButtonEmpty data-test-subj={dataTestSubjPrefix} color="text" {...propsWithoutFill}>
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Clears the following error from the test for this file:

    Warning: Received `true` for a non-boolean attribute `fill`.

    If you want to write it to the DOM, pass a string instead: fill="true" or fill={value.toString()}.
        in button (created by EuiButtonEmpty)
        in EuiButtonEmpty (created by WrapperComponent)
        in WrapperComponent

{title}
</EuiButtonEmpty>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
getDataProviderFilter,
TIMELINE_FILTER_DROP_AREA,
} from './index';
import { waitFor } from '@testing-library/dom';
Copy link
Contributor Author

Choose a reason for hiding this comment

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

clears the following error:

Warning: An update to null inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */

    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
        in Unknown (created by Proxy)
        in Provider (created by App)
        in App (created by ErrorBoundary)
        in ErrorBoundary (created by DragDropContext)
        in DragDropContext (created by TestProvidersComponent)
        in ThemeProvider (created by TestProvidersComponent)
        in Provider (created by TestProvidersComponent)
        in ApolloProvider (created by TestProvidersComponent)
        in Provider
        in Unknown (created by TestProvidersComponent)
        in PseudoLocaleWrapper (created by I18nProvider)
        in IntlProvider (created by I18nProvider)
        in I18nProvider (created by TestProvidersComponent)
        in TestProvidersComponent (created by Proxy)
        in Proxy (created by WrapperComponent)
        in WrapperComponent


const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings;

Expand Down Expand Up @@ -181,7 +182,7 @@ describe('Timeline QueryBar ', () => {
});

describe('#onSavedQuery', () => {
test('is only reference that changed when dataProviders props get updated', () => {
test('is only reference that changed when dataProviders props get updated', async () => {
const Proxy = (props: QueryBarTimelineComponentProps) => (
<TestProviders>
<QueryBarTimeline {...props} />
Expand Down Expand Up @@ -213,13 +214,13 @@ describe('Timeline QueryBar ', () => {
const onSavedQueryRef = queryBarProps.onSavedQuery;

wrapper.setProps({ dataProviders: mockDataProviders.slice(1, 0) });
wrapper.update();
await waitFor(() => wrapper.update());

expect(onSavedQueryRef).not.toEqual(wrapper.find(QueryBar).props().onSavedQuery);
expect(onSubmitQueryRef).toEqual(wrapper.find(QueryBar).props().onSubmitQuery);
});

test('is only reference that changed when savedQueryId props get updated', () => {
test('is only reference that changed when savedQueryId props get updated', async () => {
const Proxy = (props: QueryBarTimelineComponentProps) => (
<TestProviders>
<QueryBarTimeline {...props} />
Expand Down Expand Up @@ -253,7 +254,7 @@ describe('Timeline QueryBar ', () => {
wrapper.setProps({
savedQueryId: 'new',
});
wrapper.update();
await waitFor(() => wrapper.update());

expect(onSavedQueryRef).not.toEqual(wrapper.find(QueryBar).props().onSavedQuery);
expect(onSubmitQueryRef).toEqual(wrapper.find(QueryBar).props().onSubmitQuery);
Expand Down