Skip to content

Commit

Permalink
more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
stephmilovic committed Jun 8, 2020
1 parent ed20f64 commit db6ee6e
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,20 @@ describe('AllCases', () => {
};
getCasesColumns([], 'open', false).map((i, key) => i.name != null && checkIt(`${i.name}`, key));
});

it('should not render case link or actions on modal=true', () => {
const wrapper = mount(
<TestProviders>
<AllCases userCanCrud={true} isModal={true} />
</TestProviders>
);
const checkIt = (columnName: string) => {
expect(columnName).not.toEqual(i18n.ACTIONS);
};
getCasesColumns([], 'open', true).map((i, key) => i.name != null && checkIt(`${i.name}`));
expect(wrapper.find(`a[data-test-subj="case-details-link"]`).exists()).toBeFalsy();
});

it('should tableHeaderSortButton AllCases', () => {
const wrapper = mount(
<TestProviders>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ export const AllCases = React.memo<AllCasesProps>(
{(isCasesLoading || isDeleting || isUpdating) && !isDataEmpty && (
<ProgressLoader size="xs" color="accent" className="essentialAnimation" />
)}
<TableWrap loading={!isModal ? isCasesLoading : undefined}>
<TableWrap data-test-subj="table-wrap" loading={!isModal ? isCasesLoading : undefined}>
<CasesTableFilters
countClosedCases={data.countClosedCases}
countOpenCases={data.countOpenCases}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { mount } from 'enzyme';
import React from 'react';
import { AllCasesModal } from '.';
import { TestProviders } from '../../../common/mock';

import { useGetCasesMockState, basicCaseId } from '../../containers/mock';
import { useDeleteCases } from '../../containers/use_delete_cases';
import { useGetCases } from '../../containers/use_get_cases';
import { useGetCasesStatus } from '../../containers/use_get_cases_status';
import { useUpdateCases } from '../../containers/use_bulk_update_case';
import { EuiTableRow } from '@elastic/eui';

jest.mock('../../containers/use_bulk_update_case');
jest.mock('../../containers/use_delete_cases');
jest.mock('../../containers/use_get_cases');
jest.mock('../../containers/use_get_cases_status');

const useDeleteCasesMock = useDeleteCases as jest.Mock;
const useGetCasesMock = useGetCases as jest.Mock;
const useGetCasesStatusMock = useGetCasesStatus as jest.Mock;
const useUpdateCasesMock = useUpdateCases as jest.Mock;
jest.mock('../../../common/lib/kibana', () => {
const originalModule = jest.requireActual('../../../common/lib/kibana');
return {
...originalModule,
useGetUserSavedObjectPermissions: jest.fn(),
};
});

const onCloseCaseModal = jest.fn();
const onRowClick = jest.fn();
const defaultProps = {
onCloseCaseModal,
onRowClick,
showCaseModal: true,
};
describe('AllCasesModal', () => {
const dispatchResetIsDeleted = jest.fn();
const dispatchResetIsUpdated = jest.fn();
const dispatchUpdateCaseProperty = jest.fn();
const handleOnDeleteConfirm = jest.fn();
const handleToggleModal = jest.fn();
const refetchCases = jest.fn();
const setFilters = jest.fn();
const setQueryParams = jest.fn();
const setSelectedCases = jest.fn();
const updateBulkStatus = jest.fn();
const fetchCasesStatus = jest.fn();

const defaultGetCases = {
...useGetCasesMockState,
dispatchUpdateCaseProperty,
refetchCases,
setFilters,
setQueryParams,
setSelectedCases,
};
const defaultDeleteCases = {
dispatchResetIsDeleted,
handleOnDeleteConfirm,
handleToggleModal,
isDeleted: false,
isDisplayConfirmDeleteModal: false,
isLoading: false,
};
const defaultCasesStatus = {
countClosedCases: 0,
countOpenCases: 5,
fetchCasesStatus,
isError: false,
isLoading: true,
};
const defaultUpdateCases = {
isUpdated: false,
isLoading: false,
isError: false,
dispatchResetIsUpdated,
updateBulkStatus,
};
/* eslint-disable no-console */
// Silence until enzyme fixed to use ReactTestUtils.act()
const originalError = console.error;
beforeAll(() => {
console.error = jest.fn();
});
afterAll(() => {
console.error = originalError;
});
/* eslint-enable no-console */
beforeEach(() => {
jest.resetAllMocks();
useUpdateCasesMock.mockImplementation(() => defaultUpdateCases);
useGetCasesMock.mockImplementation(() => defaultGetCases);
useDeleteCasesMock.mockImplementation(() => defaultDeleteCases);
useGetCasesStatusMock.mockImplementation(() => defaultCasesStatus);
});

it('renders with unselectable rows', () => {
const wrapper = mount(
<TestProviders>
<AllCasesModal {...defaultProps} />
</TestProviders>
);
expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeTruthy();
expect(wrapper.find(EuiTableRow).first().prop('isSelectable')).toBeFalsy();
});
it('does not render modal if showCaseModal: false', () => {
const wrapper = mount(
<TestProviders>
<AllCasesModal {...{ ...defaultProps, showCaseModal: false }} />
</TestProviders>
);
expect(wrapper.find(`[data-test-subj='all-cases-modal']`).exists()).toBeFalsy();
});
it('onRowClick called when row is clicked', () => {
const wrapper = mount(
<TestProviders>
<AllCasesModal {...defaultProps} />
</TestProviders>
);
const firstRow = wrapper.find(EuiTableRow).first();
firstRow.simulate('click');
expect(onRowClick.mock.calls[0][0]).toEqual(basicCaseId);
});
it('Closing modal calls onCloseCaseModal', () => {
const wrapper = mount(
<TestProviders>
<AllCasesModal {...defaultProps} />
</TestProviders>
);
const modalClose = wrapper.find('.euiModal__closeIcon').first();
modalClose.simulate('click');
expect(onCloseCaseModal).toBeCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const AllCasesModalComponent = ({
let modal;
if (showCaseModal) {
modal = (
<EuiOverlayMask>
<EuiOverlayMask data-test-subj="all-cases-modal">
<EuiModal onClose={onCloseCaseModal}>
<EuiModalHeader>
<EuiModalHeaderTitle>{i18n.SELECT_CASE_TITLE}</EuiModalHeaderTitle>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ export const updateUrlStateString = ({
if (urlKey === CONSTANTS.appQuery) {
const queryState = decodeRisonUrlState<Query>(newUrlStateString);
if (queryState != null && queryState.query === '') {
console.log('1', history);
return replaceStateInLocation({
history,
pathName,
Expand All @@ -205,7 +204,6 @@ export const updateUrlStateString = ({
} else if (urlKey === CONSTANTS.timerange && updateTimerange) {
const queryState = decodeRisonUrlState<UrlInputsModel>(newUrlStateString);
if (queryState != null && queryState.global != null) {
console.log('2', history);
return replaceStateInLocation({
history,
pathName,
Expand All @@ -217,7 +215,6 @@ export const updateUrlStateString = ({
} else if (urlKey === CONSTANTS.filters) {
const queryState = decodeRisonUrlState<Filter[]>(newUrlStateString);
if (isEmpty(queryState)) {
console.log('3', history);
return replaceStateInLocation({
history,
pathName,
Expand All @@ -229,7 +226,6 @@ export const updateUrlStateString = ({
} else if (urlKey === CONSTANTS.timeline) {
const queryState = decodeRisonUrlState<TimelineUrl>(newUrlStateString);
if (queryState != null && queryState.id === '') {
console.log('4', history);
return replaceStateInLocation({
history,
pathName,
Expand All @@ -239,7 +235,6 @@ export const updateUrlStateString = ({
});
}
}
console.log('5', history);
return search;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@

import { mount } from 'enzyme';
import React from 'react';
import { TestProviders } from '../../../../common/mock';
import { TimelineStatus } from '../../../../../common/types/timeline';
import {
mockGlobalState,
apolloClientObservable,
SUB_PLUGINS_REDUCER,
TestProviders,
} from '../../../../common/mock';
import { createStore, State } from '../../../../common/store';
import { useThrottledResizeObserver } from '../../../../common/components/utils';
import { Properties, showDescriptionThreshold, showNotesThreshold } from '.';
import { SiemPageName } from '../../../../app/types';
import { setInsertTimeline } from '../../../store/timeline/actions';
export { nextTick } from '../../../../../../../test_utils';

import { act } from 'react-dom/test-utils';

jest.mock('../../../../common/lib/kibana', () => {
const originalModule = jest.requireActual('../../../../common/lib/kibana');
Expand All @@ -30,24 +35,21 @@ jest.mock('../../../../common/components/utils');
width: mockedWidth,
}));

jest.mock('react-redux', () => {
const originalModule = jest.requireActual('react-redux');
const mockDispatch = jest.fn();

return {
...originalModule,
useSelector: jest.fn().mockReturnValue({ savedObjectId: '1' }),
};
});

jest.mock('react-router-dom', () => {
const originalModule = jest.requireActual('react-router-dom');

return {
...originalModule,
useHistory: jest.fn(),
};
});
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: () => mockDispatch,
useSelector: jest.fn().mockReturnValue({ savedObjectId: '1', urlState: {} }),
}));
const mockHistoryPush = jest.fn();

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
const usersViewing = ['elastic'];
const defaultProps = {
associateNote: jest.fn(),
Expand Down Expand Up @@ -91,6 +93,9 @@ describe('Properties', () => {
expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual(
false
);
expect(
wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled')
).toEqual(false);
});

test('renders correctly draft timeline', () => {
Expand All @@ -105,6 +110,9 @@ describe('Properties', () => {
expect(wrapper.find('button[data-test-subj="attach-timeline-case"]').prop('disabled')).toEqual(
true
);
expect(
wrapper.find('button[data-test-subj="attach-timeline-existing-case"]').prop('disabled')
).toEqual(true);
});

test('it renders an empty star icon when it is NOT a favorite', () => {
Expand Down Expand Up @@ -284,4 +292,38 @@ describe('Properties', () => {

expect(wrapper.find('[data-test-subj="avatar"]').exists()).toEqual(false);
});

test('insert timeline - new case', () => {
const wrapper = mount(
<TestProviders store={store}>
<Properties {...{ ...defaultProps, title: 'coolness' }} />
</TestProviders>
);
wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click');
wrapper.find('[data-test-subj="attach-timeline-case"]').first().simulate('click');

expect(mockHistoryPush).toBeCalledWith({ pathname: `/${SiemPageName.case}/create` });
expect(mockDispatch).toBeCalledWith(
setInsertTimeline({
timelineId: defaultProps.timelineId,
timelineSavedObjectId: '1',
timelineTitle: 'coolness',
})
);
});

test('insert timeline - existing case', async () => {
const wrapper = mount(
<TestProviders store={store}>
<Properties {...{ ...defaultProps, title: 'coolness' }} />
</TestProviders>
);
wrapper.find('[data-test-subj="settings-gear"]').at(0).simulate('click');
wrapper.find('[data-test-subj="attach-timeline-existing-case"]').first().simulate('click');

await act(async () => {
await Promise.resolve({});
});
expect(wrapper.find('[data-test-subj="all-cases-modal"]').exists()).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import { TimelineComponent, Props as TimelineComponentProps } from './timeline';
import { Sort } from './body/sort';
import { mockDataProviders } from './data_providers/mock/mock_data_providers';
import { useMountAppended } from '../../../common/utils/use_mount_appended';
// import * as all from '../../../common/lib/kibana';
const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock;
jest.mock('use-resize-observer/polyfilled');
mockUseResizeObserver.mockImplementation(() => ({}));
Expand Down
Loading

0 comments on commit db6ee6e

Please sign in to comment.