Skip to content

Commit

Permalink
pushing changes, user_action_tree is wip
Browse files Browse the repository at this point in the history
  • Loading branch information
stephmilovic committed Apr 7, 2020
1 parent fee0a47 commit 2520299
Show file tree
Hide file tree
Showing 5 changed files with 311 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export const useCaseConfigure = ({
setLoading(true);
const res = await getCaseConfigure({ signal: abortCtrl.signal });
if (!didCancel) {
setLoading(false);
if (res != null) {
setConnector(res.connectorId, res.connectorName);
if (setClosureType != null) {
Expand All @@ -73,6 +72,7 @@ export const useCaseConfigure = ({
}
}
}
setLoading(false);
}
} catch (error) {
if (!didCancel) {
Expand Down Expand Up @@ -117,7 +117,6 @@ export const useCaseConfigure = ({
abortCtrl.signal
);
if (!didCancel) {
setPersistLoading(false);
setConnector(res.connectorId);
if (setClosureType) {
setClosureType(res.closureType);
Expand All @@ -131,6 +130,7 @@ export const useCaseConfigure = ({
}

displaySuccessToast(i18n.SUCCESS_CONFIGURE, dispatchToaster);
setPersistLoading(false);
}
} catch (error) {
if (!didCancel) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
/*
* 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.
*/
/* eslint-disable react/display-name */
// import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { usePushToService, ReturnUsePushToService, UsePushToService } from './';
import { TestProviders } from '../../../../mock';
import React from 'react';
import * as api from '../../../../containers/case/configure/api';
import { usePostPushToService } from '../../../../containers/case/use_post_push_to_service';
import { ClosureType } from '../../../../../../../../plugins/case/common/api/cases';
import * as i18n from './translations';
jest.mock('../../../../containers/case/use_post_push_to_service');
jest.mock('../../../../containers/case/configure/api');
import { useGetActionLicense } from '../../../../containers/case/use_get_action_license';
import { getKibanaConfigError, getLicenseError } from './helpers';
jest.mock('../../../../containers/case/use_get_action_license');

describe('usePushToService', () => {
const caseId = '12345';
const updateCase = jest.fn();
const postPushToService = jest.fn();
const mockPostPush = {
isLoading: false,
postPushToService,
};
const closureType: ClosureType = 'close-by-user';
const mockConnector = {
connectorId: 'c00l',
connectorName: 'name',
};
const mockCaseConfigure = {
...mockConnector,
createdAt: 'string',
createdBy: {},
closureType,
updatedAt: 'string',
updatedBy: {},
version: 'string',
};
const getConfigureMock = api.getCaseConfigure as jest.Mock;
const actionLicense = {
id: '.servicenow',
name: 'ServiceNow',
minimumLicenseRequired: 'platinum',
enabled: true,
enabledInConfig: true,
enabledInLicense: true,
};
beforeEach(() => {
jest.resetAllMocks();
(usePostPushToService as jest.Mock).mockImplementation(() => mockPostPush);
(useGetActionLicense as jest.Mock).mockImplementation(() => ({
isLoading: false,
actionLicense,
}));
getConfigureMock.mockImplementation(() => Promise.resolve(mockCaseConfigure));
});
it('push case button posts the push with correct args', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook<UsePushToService, ReturnUsePushToService>(
() =>
usePushToService({
caseId,
caseStatus: 'open',
isNew: false,
updateCase,
userCanCrud: true,
}),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
expect(getConfigureMock).toBeCalled();
result.current.pushButton.props.children.props.onClick();
expect(postPushToService).toBeCalledWith({ ...mockConnector, caseId, updateCase });
expect(result.current.pushCallouts).toBeNull();
});
});
it('Displays message when user does not have premium license', async () => {
(useGetActionLicense as jest.Mock).mockImplementation(() => ({
isLoading: false,
actionLicense: {
...actionLicense,
enabledInLicense: false,
},
}));
await act(async () => {
const { result, waitForNextUpdate } = renderHook<UsePushToService, ReturnUsePushToService>(
() =>
usePushToService({
caseId,
caseStatus: 'open',
isNew: false,
updateCase,
userCanCrud: true,
}),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const errorsMsg = result.current.pushCallouts?.props.messages;
expect(errorsMsg).toHaveLength(1);
expect(errorsMsg[0].title).toEqual(getLicenseError().title);
});
});
it('Displays message when user does not have case enabled in config', async () => {
(useGetActionLicense as jest.Mock).mockImplementation(() => ({
isLoading: false,
actionLicense: {
...actionLicense,
enabledInConfig: false,
},
}));
await act(async () => {
const { result, waitForNextUpdate } = renderHook<UsePushToService, ReturnUsePushToService>(
() =>
usePushToService({
caseId,
caseStatus: 'open',
isNew: false,
updateCase,
userCanCrud: true,
}),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const errorsMsg = result.current.pushCallouts?.props.messages;
expect(errorsMsg).toHaveLength(1);
expect(errorsMsg[0].title).toEqual(getKibanaConfigError().title);
});
});
it('Displays message when user does not have a connector configured', async () => {
getConfigureMock.mockImplementation(() =>
Promise.resolve({
...mockCaseConfigure,
connectorId: 'none',
})
);
await act(async () => {
const { result, waitForNextUpdate } = renderHook<UsePushToService, ReturnUsePushToService>(
() =>
usePushToService({
caseId,
caseStatus: 'open',
isNew: false,
updateCase,
userCanCrud: true,
}),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const errorsMsg = result.current.pushCallouts?.props.messages;
expect(errorsMsg).toHaveLength(1);
expect(errorsMsg[0].title).toEqual(i18n.PUSH_DISABLE_BY_NO_CASE_CONFIG_TITLE);
});
});
it('Displays message when case is closed', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook<UsePushToService, ReturnUsePushToService>(
() =>
usePushToService({
caseId,
caseStatus: 'closed',
isNew: false,
updateCase,
userCanCrud: true,
}),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const errorsMsg = result.current.pushCallouts?.props.messages;
expect(errorsMsg).toHaveLength(1);
expect(errorsMsg[0].title).toEqual(i18n.PUSH_DISABLE_BECAUSE_CASE_CLOSED_TITLE);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { CaseCallOut } from '../callout';
import { getLicenseError, getKibanaConfigError } from './helpers';
import * as i18n from './translations';

interface UsePushToService {
export interface UsePushToService {
caseId: string;
caseStatus: string;
isNew: boolean;
Expand All @@ -32,7 +32,7 @@ interface Connector {
connectorName: string;
}

interface ReturnUsePushToService {
export interface ReturnUsePushToService {
pushButton: JSX.Element;
pushCallouts: JSX.Element | null;
}
Expand Down Expand Up @@ -122,6 +122,7 @@ export const usePushToService = ({
const pushToServiceButton = useMemo(
() => (
<EuiButton
data-test-subj="push-to-service-now"
fill
iconType="importAction"
onClick={handlePushToService}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* 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 React from 'react';
import { mount } from 'enzyme';

import { Router, routeData, mockHistory } from '../__mock__/router';
import { UserActionTree } from './';
import { TestProviders } from '../../../../mock';
import { UserActionField } from '../../../../../../../../plugins/case/common/api/cases';

const fetchUserActions = jest.fn();
const onUpdateField = jest.fn();
const updateCase = jest.fn();
const defaultProps = {
data: {
id: '89bae2b0-74f4-11ea-a8d2-2bcd64fb2cdd',
version: 'WzcxNiwxXQ==',
comments: [],
totalComment: 0,
description: 'This looks not so good',
title: 'Bad meanie defacing data',
tags: ['defacement'],
closedAt: null,
closedBy: null,
createdAt: '2020-04-02T15:13:41.925Z',
createdBy: {
email: '[email protected]',
fullName: 'Steph Milovic',
username: 'smilovic',
},
externalService: null,
status: 'open',
updatedAt: null,
updatedBy: null,
},
caseUserActions: [],
firstIndexPushToService: -1,
isLoadingDescription: false,
isLoadingUserActions: false,
lastIndexPushToService: -1,
userCanCrud: true,
fetchUserActions,
onUpdateField,
updateCase,
};

describe.skip('UserActionTree ', () => {
beforeEach(() => {
jest.resetAllMocks();
jest.spyOn(routeData, 'useParams').mockReturnValue({ commentId: '123' });
});

it('Loading spinner when user actions loading', async () => {
const props = defaultProps;
const wrapper = mount(
<TestProviders>
<Router history={mockHistory}>
<UserActionTree {...{ ...props, isLoadingUserActions: true }} />
</Router>
</TestProviders>
);
expect(wrapper.find(`[data-test-subj="user-actions-loading"]`).exists()).toBeTruthy();
});
it.only('Renders user action items', async () => {
const commentAction = {
actionField: [('comment' as unknown) as UserActionField['comment']],
action: 'create',
actionAt: '2020-04-06T21:54:19.459Z',
actionBy: { email: '', fullName: '', username: 'casetester3' },
newValue: 'sdfsd',
oldValue: null,
actionId: '2b825fb0-7851-11ea-8b3c-092fb98f129e',
caseId: '89bae2b0-74f4-11ea-a8d2-2bcd64fb2cdd',
commentId: '2adcf7f0-7851-11ea-8b3c-092fb98f129e',
};
const props = {
...defaultProps,
caseUserActions: [commentAction],
};
const wrapper = mount(
<TestProviders>
<Router history={mockHistory}>
<UserActionTree {...props} />
</Router>
</TestProviders>
);
expect(
wrapper
.find(`[data-test-subj="comment-action"] [data-test-subj="user-action-title"] strong`)
.text()
).toEqual(commentAction.actionBy.username);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,28 @@ export const UserActionTree = React.memo(
updateCase,
userCanCrud,
}: UserActionTreeProps) => {
// console.log('userActionTree props', {
// data: caseData,
// caseUserActions,
// fetchUserActions,
// firstIndexPushToService,
// isLoadingDescription,
// isLoadingUserActions,
// lastIndexPushToService,
// onUpdateField,
// updateCase,
// userCanCrud,
// });
const { commentId } = useParams();
const handlerTimeoutId = useRef(0);
const [initLoading, setInitLoading] = useState(true);
const [selectedOutlineCommentId, setSelectedOutlineCommentId] = useState('');
const { isLoadingIds, patchComment } = useUpdateComment();
// console.log('useUpdateComment', { isLoadingIds, patchComment })
const currentUser = useCurrentUser();
// console.log('useCurrentUser', currentUser)
const [manageMarkdownEditIds, setManangeMardownEditIds] = useState<string[]>([]);
const [insertQuote, setInsertQuote] = useState<string | null>(null);

const handleManageMarkdownEditId = useCallback(
(id: string) => {
if (!manageMarkdownEditIds.includes(id)) {
Expand Down Expand Up @@ -237,6 +250,7 @@ export const UserActionTree = React.memo(
<UserActionItem
key={action.actionId}
createdAt={action.actionAt}
data-test-subj="comment-action"
disabled={!userCanCrud}
id={action.actionId}
isEditable={false}
Expand Down Expand Up @@ -264,7 +278,7 @@ export const UserActionTree = React.memo(
{(isLoadingUserActions || isLoadingIds.includes(NEW_ID)) && (
<MyEuiFlexGroup justifyContent="center" alignItems="center">
<EuiFlexItem grow={false}>
<EuiLoadingSpinner size="l" />
<EuiLoadingSpinner data-test-subj="user-actions-loading" size="l" />
</EuiFlexItem>
</MyEuiFlexGroup>
)}
Expand Down

0 comments on commit 2520299

Please sign in to comment.