diff --git a/x-pack/plugins/lists/public/common/mocks/kibana_core.ts b/x-pack/plugins/lists/public/common/mocks/kibana_core.ts deleted file mode 100644 index c078e8ccd5ea..000000000000 --- a/x-pack/plugins/lists/public/common/mocks/kibana_core.ts +++ /dev/null @@ -1,12 +0,0 @@ -/* - * 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 { coreMock } from '../../../../../../src/core/public/mocks'; -import { CoreStart } from '../../../../../../src/core/public'; - -export type GlobalServices = Pick; - -export const createKibanaCoreStartMock = (): GlobalServices => coreMock.createStart(); diff --git a/x-pack/plugins/lists/public/exceptions/api.test.ts b/x-pack/plugins/lists/public/exceptions/api.test.ts index 9add15c533d1..457a8708ec34 100644 --- a/x-pack/plugins/lists/public/exceptions/api.test.ts +++ b/x-pack/plugins/lists/public/exceptions/api.test.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { createKibanaCoreStartMock } from '../common/mocks/kibana_core'; +import { coreMock } from '../../../../../src/core/public/mocks'; import { getExceptionListSchemaMock } from '../../common/schemas/response/exception_list_schema.mock'; import { getExceptionListItemSchemaMock } from '../../common/schemas/response/exception_list_item_schema.mock'; import { getCreateExceptionListSchemaMock } from '../../common/schemas/request/create_exception_list_schema.mock'; @@ -34,39 +34,28 @@ import { ApiCallByIdProps, ApiCallByListIdProps } from './types'; const abortCtrl = new AbortController(); -jest.mock('../common/mocks/kibana_core', () => ({ - createKibanaCoreStartMock: (): jest.Mock => jest.fn(), -})); -const fetchMock = jest.fn(); - -/* - This is a little funky, in order for typescript to not - yell at us for converting 'Pick' to type 'Mock' - have to first convert to type 'unknown' - */ -const mockKibanaHttpService = ((createKibanaCoreStartMock() as unknown) as jest.Mock).mockReturnValue( - { - fetch: fetchMock, - } -); - describe('Exceptions Lists API', () => { + let httpMock: ReturnType['http']; + + beforeEach(() => { + httpMock = coreMock.createStart().http; + }); + describe('#addExceptionList', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListSchemaMock()); }); test('it invokes "addExceptionList" with expected url and body values', async () => { const payload = getCreateExceptionListSchemaMock(); await addExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }); // TODO Would like to just use getExceptionListSchemaMock() here, but // validation returns object in different order, making the strings not match - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists', { body: JSON.stringify(payload), method: 'POST', signal: abortCtrl.signal, @@ -76,7 +65,7 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const payload = getCreateExceptionListSchemaMock(); const exceptionResponse = await addExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }); @@ -90,7 +79,7 @@ describe('Exceptions Lists API', () => { await expect( addExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: (payload as unknown) as ExceptionListSchema, signal: abortCtrl.signal, }) @@ -101,11 +90,11 @@ describe('Exceptions Lists API', () => { const payload = getCreateExceptionListSchemaMock(); const badPayload = getExceptionListSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( addExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }) @@ -115,20 +104,19 @@ describe('Exceptions Lists API', () => { describe('#addExceptionListItem', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListItemSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListItemSchemaMock()); }); test('it invokes "addExceptionListItem" with expected url and body values', async () => { const payload = getCreateExceptionListItemSchemaMock(); await addExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }); // TODO Would like to just use getExceptionListSchemaMock() here, but // validation returns object in different order, making the strings not match - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items', { body: JSON.stringify(payload), method: 'POST', signal: abortCtrl.signal, @@ -138,7 +126,7 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const payload = getCreateExceptionListItemSchemaMock(); const exceptionResponse = await addExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }); @@ -152,7 +140,7 @@ describe('Exceptions Lists API', () => { await expect( addExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: (payload as unknown) as ExceptionListItemSchema, signal: abortCtrl.signal, }) @@ -163,11 +151,11 @@ describe('Exceptions Lists API', () => { const payload = getCreateExceptionListItemSchemaMock(); const badPayload = getExceptionListItemSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( addExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }) @@ -177,20 +165,19 @@ describe('Exceptions Lists API', () => { describe('#updateExceptionList', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListSchemaMock()); }); test('it invokes "updateExceptionList" with expected url and body values', async () => { const payload = getUpdateExceptionListSchemaMock(); await updateExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }); // TODO Would like to just use getExceptionListSchemaMock() here, but // validation returns object in different order, making the strings not match - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists', { body: JSON.stringify(payload), method: 'PUT', signal: abortCtrl.signal, @@ -200,7 +187,7 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const payload = getUpdateExceptionListSchemaMock(); const exceptionResponse = await updateExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }); @@ -213,7 +200,7 @@ describe('Exceptions Lists API', () => { await expect( updateExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }) @@ -224,11 +211,11 @@ describe('Exceptions Lists API', () => { const payload = getUpdateExceptionListSchemaMock(); const badPayload = getExceptionListSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( updateExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, list: payload, signal: abortCtrl.signal, }) @@ -238,20 +225,19 @@ describe('Exceptions Lists API', () => { describe('#updateExceptionListItem', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListItemSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListItemSchemaMock()); }); test('it invokes "updateExceptionListItem" with expected url and body values', async () => { const payload = getUpdateExceptionListItemSchemaMock(); await updateExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }); // TODO Would like to just use getExceptionListSchemaMock() here, but // validation returns object in different order, making the strings not match - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items', { body: JSON.stringify(payload), method: 'PUT', signal: abortCtrl.signal, @@ -261,7 +247,7 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const payload = getUpdateExceptionListItemSchemaMock(); const exceptionResponse = await updateExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }); @@ -274,7 +260,7 @@ describe('Exceptions Lists API', () => { await expect( updateExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }) @@ -285,11 +271,11 @@ describe('Exceptions Lists API', () => { const payload = getUpdateExceptionListItemSchemaMock(); const badPayload = getExceptionListItemSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( updateExceptionListItem({ - http: mockKibanaHttpService(), + http: httpMock, listItem: payload, signal: abortCtrl.signal, }) @@ -299,18 +285,17 @@ describe('Exceptions Lists API', () => { describe('#fetchExceptionListById', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListSchemaMock()); }); test('it invokes "fetchExceptionListById" with expected url and body values', async () => { await fetchExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists', { method: 'GET', query: { id: '1', @@ -322,7 +307,7 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const exceptionResponse = await fetchExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -332,7 +317,7 @@ describe('Exceptions Lists API', () => { test('it returns error and does not make request if request payload fails decode', async () => { const payload = ({ - http: mockKibanaHttpService(), + http: httpMock, id: 1, namespaceType: 'single', signal: abortCtrl.signal, @@ -345,11 +330,11 @@ describe('Exceptions Lists API', () => { test('it returns error if response payload fails decode', async () => { const badPayload = getExceptionListSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( fetchExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -360,14 +345,13 @@ describe('Exceptions Lists API', () => { describe('#fetchExceptionListsItemsByListIds', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getFoundExceptionListItemSchemaMock()); + httpMock.fetch.mockResolvedValue(getFoundExceptionListItemSchemaMock()); }); test('it invokes "fetchExceptionListsItemsByListIds" with expected url and body values', async () => { await fetchExceptionListsItemsByListIds({ filterOptions: [], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList', 'myOtherListId'], namespaceTypes: ['single', 'single'], pagination: { @@ -377,7 +361,7 @@ describe('Exceptions Lists API', () => { signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items/_find', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items/_find', { method: 'GET', query: { list_id: 'myList,myOtherListId', @@ -397,7 +381,7 @@ describe('Exceptions Lists API', () => { tags: [], }, ], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['single'], pagination: { @@ -407,7 +391,7 @@ describe('Exceptions Lists API', () => { signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items/_find', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items/_find', { method: 'GET', query: { filter: 'exception-list.attributes.entries.field:hello world*', @@ -428,7 +412,7 @@ describe('Exceptions Lists API', () => { tags: [], }, ], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['agnostic'], pagination: { @@ -438,7 +422,7 @@ describe('Exceptions Lists API', () => { signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items/_find', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items/_find', { method: 'GET', query: { filter: 'exception-list-agnostic.attributes.entries.field:hello world*', @@ -459,7 +443,7 @@ describe('Exceptions Lists API', () => { tags: ['malware'], }, ], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['agnostic'], pagination: { @@ -469,7 +453,7 @@ describe('Exceptions Lists API', () => { signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items/_find', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items/_find', { method: 'GET', query: { filter: 'exception-list-agnostic.attributes.tags:malware', @@ -490,7 +474,7 @@ describe('Exceptions Lists API', () => { tags: ['malware'], }, ], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['agnostic'], pagination: { @@ -500,7 +484,7 @@ describe('Exceptions Lists API', () => { signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items/_find', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items/_find', { method: 'GET', query: { filter: @@ -517,7 +501,7 @@ describe('Exceptions Lists API', () => { test('it returns expected format when call succeeds', async () => { const exceptionResponse = await fetchExceptionListsItemsByListIds({ filterOptions: [], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['endpoint_list_id'], namespaceTypes: ['single'], pagination: { @@ -532,7 +516,7 @@ describe('Exceptions Lists API', () => { test('it returns error and does not make request if request payload fails decode', async () => { const payload = ({ filterOptions: [], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['not a namespace type'], pagination: { @@ -549,12 +533,12 @@ describe('Exceptions Lists API', () => { test('it returns error if response payload fails decode', async () => { const badPayload = getExceptionListItemSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( fetchExceptionListsItemsByListIds({ filterOptions: [], - http: mockKibanaHttpService(), + http: httpMock, listIds: ['myList'], namespaceTypes: ['single'], pagination: { @@ -571,18 +555,17 @@ describe('Exceptions Lists API', () => { describe('#fetchExceptionListItemById', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListItemSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListItemSchemaMock()); }); test('it invokes "fetchExceptionListItemById" with expected url and body values', async () => { await fetchExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items', { method: 'GET', query: { id: '1', @@ -594,7 +577,7 @@ describe('Exceptions Lists API', () => { test('it returns expected format when call succeeds', async () => { const exceptionResponse = await fetchExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -604,7 +587,7 @@ describe('Exceptions Lists API', () => { test('it returns error and does not make request if request payload fails decode', async () => { const payload = ({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'not a namespace type', signal: abortCtrl.signal, @@ -617,11 +600,11 @@ describe('Exceptions Lists API', () => { test('it returns error if response payload fails decode', async () => { const badPayload = getExceptionListItemSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( fetchExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -632,18 +615,17 @@ describe('Exceptions Lists API', () => { describe('#deleteExceptionListById', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListSchemaMock()); }); test('check parameter url, body when deleting exception item', async () => { await deleteExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists', { method: 'DELETE', query: { id: '1', @@ -655,7 +637,7 @@ describe('Exceptions Lists API', () => { test('it returns expected format when call succeeds', async () => { const exceptionResponse = await deleteExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -665,7 +647,7 @@ describe('Exceptions Lists API', () => { test('it returns error and does not make request if request payload fails decode', async () => { const payload = ({ - http: mockKibanaHttpService(), + http: httpMock, id: 1, namespaceType: 'single', signal: abortCtrl.signal, @@ -678,11 +660,11 @@ describe('Exceptions Lists API', () => { test('it returns error if response payload fails decode', async () => { const badPayload = getExceptionListSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( deleteExceptionListById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -693,18 +675,17 @@ describe('Exceptions Lists API', () => { describe('#deleteExceptionListItemById', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListItemSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListItemSchemaMock()); }); test('check parameter url, body when deleting exception item', async () => { await deleteExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/exception_lists/items', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/exception_lists/items', { method: 'DELETE', query: { id: '1', @@ -716,7 +697,7 @@ describe('Exceptions Lists API', () => { test('it returns expected format when call succeeds', async () => { const exceptionResponse = await deleteExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -726,7 +707,7 @@ describe('Exceptions Lists API', () => { test('it returns error and does not make request if request payload fails decode', async () => { const payload = ({ - http: mockKibanaHttpService(), + http: httpMock, id: 1, namespaceType: 'single', signal: abortCtrl.signal, @@ -739,11 +720,11 @@ describe('Exceptions Lists API', () => { test('it returns error if response payload fails decode', async () => { const badPayload = getExceptionListItemSchemaMock(); delete badPayload.id; - fetchMock.mockResolvedValue(badPayload); + httpMock.fetch.mockResolvedValue(badPayload); await expect( deleteExceptionListItemById({ - http: mockKibanaHttpService(), + http: httpMock, id: '1', namespaceType: 'single', signal: abortCtrl.signal, @@ -754,16 +735,15 @@ describe('Exceptions Lists API', () => { describe('#addEndpointExceptionList', () => { beforeEach(() => { - fetchMock.mockClear(); - fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + httpMock.fetch.mockResolvedValue(getExceptionListSchemaMock()); }); test('it invokes "addEndpointExceptionList" with expected url and body values', async () => { await addEndpointExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, signal: abortCtrl.signal, }); - expect(fetchMock).toHaveBeenCalledWith('/api/endpoint_list', { + expect(httpMock.fetch).toHaveBeenCalledWith('/api/endpoint_list', { method: 'POST', signal: abortCtrl.signal, }); @@ -771,16 +751,16 @@ describe('Exceptions Lists API', () => { test('it returns expected exception list on success', async () => { const exceptionResponse = await addEndpointExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, signal: abortCtrl.signal, }); expect(exceptionResponse).toEqual(getExceptionListSchemaMock()); }); test('it returns an empty object when list already exists', async () => { - fetchMock.mockResolvedValue({}); + httpMock.fetch.mockResolvedValue({}); const exceptionResponse = await addEndpointExceptionList({ - http: mockKibanaHttpService(), + http: httpMock, signal: abortCtrl.signal, }); expect(exceptionResponse).toEqual({}); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts b/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts index ebee2cbace9c..9460432cbc9c 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts +++ b/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_item.test.ts @@ -6,16 +6,16 @@ import { act, renderHook } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../src/core/public/mocks'; import * as api from '../api'; import { getCreateExceptionListItemSchemaMock } from '../../../common/schemas/request/create_exception_list_item_schema.mock'; import { getUpdateExceptionListItemSchemaMock } from '../../../common/schemas/request/update_exception_list_item_schema.mock'; import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; -import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { PersistHookProps } from '../types'; import { ReturnPersistExceptionItem, usePersistExceptionItem } from './persist_exception_item'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; describe('usePersistExceptionItem', () => { const onError = jest.fn(); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts b/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts index 0541f893e279..d5dfe1174d00 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts +++ b/x-pack/plugins/lists/public/exceptions/hooks/persist_exception_list.test.ts @@ -6,16 +6,16 @@ import { act, renderHook } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../src/core/public/mocks'; import * as api from '../api'; import { getCreateExceptionListSchemaMock } from '../../../common/schemas/request/create_exception_list_schema.mock'; import { getUpdateExceptionListSchemaMock } from '../../../common/schemas/request/update_exception_list_schema.mock'; import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; -import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { PersistHookProps } from '../types'; import { ReturnPersistExceptionList, usePersistExceptionList } from './persist_exception_list'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; describe('usePersistExceptionList', () => { const onError = jest.fn(); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts b/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts index c93155274937..6469dc49c460 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.ts @@ -6,8 +6,8 @@ import { act, renderHook } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../src/core/public/mocks'; import * as api from '../api'; -import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; import { getFoundExceptionListItemSchemaMock } from '../../../common/schemas/response/found_exception_list_item_schema.mock'; import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; @@ -16,7 +16,7 @@ import { ApiCallByIdProps, ApiCallByListIdProps } from '../types'; import { ExceptionsApi, useApi } from './use_api'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; describe('useApi', () => { const onErrorMock = jest.fn(); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts index 3a8b1713b901..5c544c7e96e3 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.ts @@ -6,15 +6,15 @@ import { act, renderHook } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../src/core/public/mocks'; import * as api from '../api'; -import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { getFoundExceptionListItemSchemaMock } from '../../../common/schemas/response/found_exception_list_item_schema.mock'; import { ExceptionListItemSchema } from '../../../common/schemas'; import { UseExceptionListProps, UseExceptionListSuccess } from '../types'; import { ReturnExceptionListAndItems, useExceptionList } from './use_exception_list'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; describe('useExceptionList', () => { const onErrorMock = jest.fn(); diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index f5ed151ebac3..e6e082321419 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -15,7 +15,6 @@ import { useGetCasesMockState } from '../../containers/mock'; import * as i18n from './translations'; import { useKibana } from '../../../common/lib/kibana'; -import { createUseKibanaMock } from '../../../common/mock/kibana_react'; import { getEmptyTagValue } from '../../../common/components/empty_value'; import { useDeleteCases } from '../../containers/use_delete_cases'; import { useGetCases } from '../../containers/use_get_cases'; @@ -28,7 +27,7 @@ jest.mock('../../containers/use_delete_cases'); jest.mock('../../containers/use_get_cases'); jest.mock('../../containers/use_get_cases_status'); -const useKibanaMock = useKibana as jest.Mock; +const useKibanaMock = useKibana as jest.Mocked; const useDeleteCasesMock = useDeleteCases as jest.Mock; const useGetCasesMock = useGetCases as jest.Mock; const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; @@ -97,23 +96,16 @@ describe('AllCases', () => { }); /* eslint-enable no-console */ beforeEach(() => { - jest.resetAllMocks(); + jest.clearAllMocks(); navigateToApp = jest.fn(); - const kibanaMock = createUseKibanaMock()(); - useKibanaMock.mockReturnValue({ - ...kibanaMock, - services: { - application: { - navigateToApp, - }, - }, - }); + useKibanaMock().services.application.navigateToApp = navigateToApp; useUpdateCasesMock.mockReturnValue(defaultUpdateCases); useGetCasesMock.mockReturnValue(defaultGetCases); useDeleteCasesMock.mockReturnValue(defaultDeleteCases); useGetCasesStatusMock.mockReturnValue(defaultCasesStatus); moment.tz.setDefault('UTC'); }); + it('should render AllCases', () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/cases/components/configure_cases/__mock__/index.tsx b/x-pack/plugins/security_solution/public/cases/components/configure_cases/__mock__/index.tsx index 23c76953a6a0..08303ddc9397 100644 --- a/x-pack/plugins/security_solution/public/cases/components/configure_cases/__mock__/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/configure_cases/__mock__/index.tsx @@ -8,10 +8,7 @@ import { Connector } from '../../../containers/configure/types'; import { ReturnConnectors } from '../../../containers/configure/use_connectors'; import { connectorsMock } from '../../../containers/configure/mock'; import { ReturnUseCaseConfigure } from '../../../containers/configure/use_configure'; -import { createUseKibanaMock } from '../../../../common/mock/kibana_react'; export { mapping } from '../../../containers/configure/mock'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { actionTypeRegistryMock } from '../../../../../../triggers_actions_ui/public/application/action_type_registry.mock'; export const connectors: Connector[] = connectorsMock; @@ -46,10 +43,3 @@ export const useConnectorsResponse: ReturnConnectors = { connectors, refetchConnectors: jest.fn(), }; - -export const kibanaMockImplementationArgs = { - services: { - ...createUseKibanaMock()().services, - triggers_actions_ui: { actionTypeRegistry: actionTypeRegistryMock.create() }, - }, -}; diff --git a/x-pack/plugins/security_solution/public/cases/components/configure_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/configure_cases/index.test.tsx index 7974116f4dc4..3c17a9191d20 100644 --- a/x-pack/plugins/security_solution/public/cases/components/configure_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/configure_cases/index.test.tsx @@ -15,38 +15,39 @@ import { ActionsConnectorsContextProvider, ConnectorAddFlyout, ConnectorEditFlyout, + TriggersAndActionsUIPublicPluginStart, } from '../../../../../triggers_actions_ui/public'; +import { actionTypeRegistryMock } from '../../../../../triggers_actions_ui/public/application/action_type_registry.mock'; import { useKibana } from '../../../common/lib/kibana'; import { useConnectors } from '../../containers/configure/use_connectors'; import { useCaseConfigure } from '../../containers/configure/use_configure'; import { useGetUrlSearch } from '../../../common/components/navigation/use_get_url_search'; -import { - connectors, - searchURL, - useCaseConfigureResponse, - useConnectorsResponse, - kibanaMockImplementationArgs, -} from './__mock__'; +import { connectors, searchURL, useCaseConfigureResponse, useConnectorsResponse } from './__mock__'; jest.mock('../../../common/lib/kibana'); jest.mock('../../containers/configure/use_connectors'); jest.mock('../../containers/configure/use_configure'); jest.mock('../../../common/components/navigation/use_get_url_search'); -const useKibanaMock = useKibana as jest.Mock; +const useKibanaMock = useKibana as jest.Mocked; const useConnectorsMock = useConnectors as jest.Mock; const useCaseConfigureMock = useCaseConfigure as jest.Mock; const useGetUrlSearchMock = useGetUrlSearch as jest.Mock; + describe('ConfigureCases', () => { + beforeEach(() => { + useKibanaMock().services.triggers_actions_ui = ({ + actionTypeRegistry: actionTypeRegistryMock.create(), + } as unknown) as TriggersAndActionsUIPublicPluginStart; + }); + describe('rendering', () => { let wrapper: ReactWrapper; beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => useCaseConfigureResponse); useConnectorsMock.mockImplementation(() => ({ ...useConnectorsResponse, connectors: [] })); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); @@ -84,8 +85,8 @@ describe('ConfigureCases', () => { describe('Unhappy path', () => { let wrapper: ReactWrapper; + beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, closureType: 'close-by-user', @@ -98,7 +99,6 @@ describe('ConfigureCases', () => { }, })); useConnectorsMock.mockImplementation(() => ({ ...useConnectorsResponse, connectors: [] })); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); }); @@ -122,7 +122,6 @@ describe('ConfigureCases', () => { let wrapper: ReactWrapper; beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, mapping: connectors[0].config.incidentConfiguration.mapping, @@ -136,7 +135,6 @@ describe('ConfigureCases', () => { }, })); useConnectorsMock.mockImplementation(() => useConnectorsResponse); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); @@ -211,9 +209,6 @@ describe('ConfigureCases', () => { let wrapper: ReactWrapper; beforeEach(() => { - jest.resetAllMocks(); - jest.restoreAllMocks(); - jest.clearAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, mapping: connectors[1].config.incidentConfiguration.mapping, @@ -230,7 +225,6 @@ describe('ConfigureCases', () => { ...useConnectorsResponse, loading: true, })); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); }); @@ -262,7 +256,6 @@ describe('ConfigureCases', () => { let wrapper: ReactWrapper; beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, connectorId: 'servicenow-1', @@ -270,7 +263,6 @@ describe('ConfigureCases', () => { })); useConnectorsMock.mockImplementation(() => useConnectorsResponse); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); }); @@ -305,7 +297,6 @@ describe('ConfigureCases', () => { let wrapper: ReactWrapper; beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, loading: true, @@ -313,7 +304,6 @@ describe('ConfigureCases', () => { useConnectorsMock.mockImplementation(() => ({ ...useConnectorsResponse, })); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); }); @@ -329,10 +319,10 @@ describe('ConfigureCases', () => { describe('connectors', () => { let wrapper: ReactWrapper; - const persistCaseConfigure = jest.fn(); + let persistCaseConfigure: jest.Mock; beforeEach(() => { - jest.resetAllMocks(); + persistCaseConfigure = jest.fn(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, mapping: connectors[0].config.incidentConfiguration.mapping, @@ -347,7 +337,6 @@ describe('ConfigureCases', () => { persistCaseConfigure, })); useConnectorsMock.mockImplementation(() => useConnectorsResponse); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); @@ -396,10 +385,10 @@ describe('ConfigureCases', () => { describe('closure options', () => { let wrapper: ReactWrapper; - const persistCaseConfigure = jest.fn(); + let persistCaseConfigure: jest.Mock; beforeEach(() => { - jest.resetAllMocks(); + persistCaseConfigure = jest.fn(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, mapping: connectors[0].config.incidentConfiguration.mapping, @@ -414,7 +403,6 @@ describe('closure options', () => { persistCaseConfigure, })); useConnectorsMock.mockImplementation(() => useConnectorsResponse); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); wrapper = mount(, { wrappingComponent: TestProviders }); @@ -435,7 +423,6 @@ describe('closure options', () => { describe('user interactions', () => { beforeEach(() => { - jest.resetAllMocks(); useCaseConfigureMock.mockImplementation(() => ({ ...useCaseConfigureResponse, mapping: connectors[1].config.incidentConfiguration.mapping, @@ -449,7 +436,6 @@ describe('user interactions', () => { }, })); useConnectorsMock.mockImplementation(() => useConnectorsResponse); - useKibanaMock.mockImplementation(() => kibanaMockImplementationArgs); useGetUrlSearchMock.mockImplementation(() => searchURL); }); diff --git a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx index b5bf68cbf6dc..3b203e81cd07 100644 --- a/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/use_all_cases_modal/index.test.tsx @@ -14,26 +14,17 @@ import '../../../common/mock/match_media'; import { TimelineId } from '../../../../common/types/timeline'; import { useAllCasesModal, UseAllCasesModalProps, UseAllCasesModalReturnedValues } from '.'; import { TestProviders } from '../../../common/mock'; -import { createUseKibanaMock } from '../../../common/mock/kibana_react'; jest.mock('../../../common/lib/kibana'); -const useKibanaMock = useKibana as jest.Mock; +const useKibanaMock = useKibana as jest.Mocked; describe('useAllCasesModal', () => { - const navigateToApp = jest.fn(() => Promise.resolve()); + let navigateToApp: jest.Mock; beforeEach(() => { - jest.clearAllMocks(); - const kibanaMock = createUseKibanaMock()(); - useKibanaMock.mockImplementation(() => ({ - ...kibanaMock, - services: { - application: { - navigateToApp, - }, - }, - })); + navigateToApp = jest.fn(); + useKibanaMock().services.application.navigateToApp = navigateToApp; }); it('init', async () => { diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx index 8e76a88572e4..b53da42da55f 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx @@ -7,12 +7,12 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { useWithSource } from '../../containers/source'; import { mockBrowserFields } from '../../containers/source/mock'; import '../../mock/match_media'; import { useKibana } from '../../lib/kibana'; import { TestProviders } from '../../mock'; -import { createKibanaCoreStartMock } from '../../mock/kibana_core'; import { FilterManager } from '../../../../../../../src/plugins/data/public'; import { useAddToTimeline } from '../../hooks/use_add_to_timeline'; @@ -60,7 +60,7 @@ jest.mock('../../../timelines/components/manage_timeline', () => { }; }); -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; const timelineId = TimelineId.active; const field = 'process.name'; const value = 'nice'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx index 2b713636862b..cef92ce2a781 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.test.tsx @@ -11,14 +11,13 @@ import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { act } from 'react-dom/test-utils'; import { AddExceptionModal } from './'; -import { useKibana, useCurrentUser } from '../../../../common/lib/kibana'; +import { useCurrentUser } from '../../../../common/lib/kibana'; import { getExceptionListSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_schema.mock'; import { useFetchIndexPatterns } from '../../../../detections/containers/detection_engine/rules'; import { stubIndexPattern } from 'src/plugins/data/common/index_patterns/index_pattern.stub'; import { useAddOrUpdateException } from '../use_add_exception'; import { useFetchOrCreateRuleExceptionList } from '../use_fetch_or_create_rule_exception_list'; import { useSignalIndex } from '../../../../detections/containers/detection_engine/alerts/use_signal_index'; -import { createUseKibanaMock } from '../../../mock/kibana_react'; import { TimelineNonEcsData, Ecs } from '../../../../graphql/types'; import * as builder from '../builder'; import * as helpers from '../helpers'; @@ -33,8 +32,6 @@ jest.mock('../use_add_exception'); jest.mock('../use_fetch_or_create_rule_exception_list'); jest.mock('../builder'); -const useKibanaMock = useKibana as jest.Mock; - describe('When the add exception modal is opened', () => { const ruleName = 'test rule'; let defaultEndpointItems: jest.SpyInstance { .spyOn(builder, 'ExceptionBuilderComponent') .mockReturnValue(<>); - const kibanaMock = createUseKibanaMock()(); - useKibanaMock.mockImplementation(() => ({ - ...kibanaMock, - })); (useAddOrUpdateException as jest.Mock).mockImplementation(() => [ { isLoading: false }, jest.fn(), diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx index 8ad80eba569c..6ff218ca0605 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.test.tsx @@ -11,7 +11,7 @@ import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { act } from 'react-dom/test-utils'; import { EditExceptionModal } from './'; -import { useKibana, useCurrentUser } from '../../../../common/lib/kibana'; +import { useCurrentUser } from '../../../../common/lib/kibana'; import { useFetchIndexPatterns } from '../../../../detections/containers/detection_engine/rules'; import { stubIndexPattern, @@ -19,7 +19,6 @@ import { } from 'src/plugins/data/common/index_patterns/index_pattern.stub'; import { useAddOrUpdateException } from '../use_add_exception'; import { useSignalIndex } from '../../../../detections/containers/detection_engine/alerts/use_signal_index'; -import { createUseKibanaMock } from '../../../mock/kibana_react'; import { getExceptionListItemSchemaMock } from '../../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; import { EntriesArray } from '../../../../../../lists/common/schemas/types'; import * as builder from '../builder'; @@ -31,8 +30,6 @@ jest.mock('../use_fetch_or_create_rule_exception_list'); jest.mock('../../../../detections/containers/detection_engine/alerts/use_signal_index'); jest.mock('../builder'); -const useKibanaMock = useKibana as jest.Mock; - describe('When the edit exception modal is opened', () => { const ruleName = 'test rule'; @@ -45,10 +42,6 @@ describe('When the edit exception modal is opened', () => { .spyOn(builder, 'ExceptionBuilderComponent') .mockReturnValue(<>); - const kibanaMock = createUseKibanaMock()(); - useKibanaMock.mockImplementation(() => ({ - ...kibanaMock, - })); (useSignalIndex as jest.Mock).mockReturnValue({ loading: false, signalIndexName: 'test-signal', diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx index cb1a80abedb2..6611ee2385d1 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx @@ -5,6 +5,7 @@ */ import { act, renderHook, RenderHookResult } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { KibanaServices } from '../../../common/lib/kibana'; import * as alertsApi from '../../../detections/containers/detection_engine/alerts/api'; @@ -14,7 +15,6 @@ import * as buildAlertStatusFilterHelper from '../../../detections/components/al import { getExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; import { getCreateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/create_exception_list_item_schema.mock'; import { getUpdateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/update_exception_list_item_schema.mock'; -import { createKibanaCoreStartMock } from '../../../common/mock/kibana_core'; import { ExceptionListItemSchema, CreateExceptionListItemSchema, @@ -27,7 +27,7 @@ import { AddOrUpdateExceptionItemsFunc, } from './use_add_exception'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; const mockKibanaServices = KibanaServices.get as jest.Mock; jest.mock('../../../common/lib/kibana'); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx index 6dbf5922e0a9..39d88bd8e472 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx @@ -6,11 +6,11 @@ import { act, renderHook, RenderHookResult } from '@testing-library/react-hooks'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import * as rulesApi from '../../../detections/containers/detection_engine/rules/api'; import * as listsApi from '../../../../../lists/public/exceptions/api'; import { getExceptionListSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_schema.mock'; import { savedRuleMock } from '../../../detections/containers/detection_engine/rules/mock'; -import { createKibanaCoreStartMock } from '../../mock/kibana_core'; import { ExceptionListType } from '../../../lists_plugin_deps'; import { ListArray } from '../../../../common/detection_engine/schemas/types'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; @@ -20,7 +20,7 @@ import { ReturnUseFetchOrCreateRuleExceptionList, } from './use_fetch_or_create_rule_exception_list'; -const mockKibanaHttpService = createKibanaCoreStartMock().http; +const mockKibanaHttpService = coreMock.createStart().http; jest.mock('../../../detections/containers/detection_engine/rules/api'); describe('useFetchOrCreateRuleExceptionList', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/ml/hooks/use_installed_security_jobs.ts b/x-pack/plugins/security_solution/public/common/components/ml/hooks/use_installed_security_jobs.ts index a9a728f81cc6..dde5eebe624b 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/hooks/use_installed_security_jobs.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/hooks/use_installed_security_jobs.ts @@ -29,6 +29,9 @@ export interface UseInstalledSecurityJobsReturn { * Use the corresponding helper functions to filter the job list as * necessary (running jobs, etc). * + * NOTE: If you need to include jobs that are not currently installed, try the + * {@link useInstalledSecurityJobs} hook. + * */ export const useInstalledSecurityJobs = (): UseInstalledSecurityJobsReturn => { const [jobs, setJobs] = useState([]); diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_security_jobs.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_security_jobs.ts index e8809e8366ee..2ba5cb84d272 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_security_jobs.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/hooks/use_security_jobs.ts @@ -32,6 +32,7 @@ export interface UseSecurityJobsReturn { * list as necessary. E.g. installed jobs, running jobs, etc. * * NOTE: If the user is not an ml admin, jobs will be empty and isMlAdmin will be false. + * If you only need installed jobs, try the {@link useInstalledSecurityJobs} hook. * * @param refetchData */ @@ -39,7 +40,7 @@ export const useSecurityJobs = (refetchData: boolean): UseSecurityJobsReturn => const [jobs, setJobs] = useState([]); const [loading, setLoading] = useState(true); const mlCapabilities = useMlCapabilities(); - const [siemDefaultIndex] = useUiSetting$(DEFAULT_INDEX_KEY); + const [securitySolutionDefaultIndex] = useUiSetting$(DEFAULT_INDEX_KEY); const http = useHttp(); const { addError } = useAppToasts(); @@ -54,12 +55,12 @@ export const useSecurityJobs = (refetchData: boolean): UseSecurityJobsReturn => async function fetchSecurityJobIdsFromGroupsData() { if (isMlAdmin && isLicensed) { try { - // Batch fetch all installed jobs, ML modules, and check which modules are compatible with siemDefaultIndex + // Batch fetch all installed jobs, ML modules, and check which modules are compatible with securitySolutionDefaultIndex const [jobSummaryData, modulesData, compatibleModules] = await Promise.all([ getJobsSummary({ http, signal: abortCtrl.signal }), getModules({ signal: abortCtrl.signal }), checkRecognizer({ - indexPatternName: siemDefaultIndex, + indexPatternName: securitySolutionDefaultIndex, signal: abortCtrl.signal, }), ]); @@ -89,7 +90,7 @@ export const useSecurityJobs = (refetchData: boolean): UseSecurityJobsReturn => isSubscribed = false; abortCtrl.abort(); }; - }, [refetchData, isMlAdmin, isLicensed, siemDefaultIndex, addError, http]); + }, [refetchData, isMlAdmin, isLicensed, securitySolutionDefaultIndex, addError, http]); return { isLicensed, isMlAdmin, jobs, loading }; }; diff --git a/x-pack/plugins/security_solution/public/common/components/ml_popover/types.ts b/x-pack/plugins/security_solution/public/common/components/ml_popover/types.ts index c839f5110fe7..7120fcf4a9e5 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml_popover/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml_popover/types.ts @@ -111,7 +111,7 @@ export interface CustomURL { } /** - * Representation of an ML Job as used by the SIEM App -- a composition of ModuleJob and MlSummaryJob + * Representation of an ML Job as used by the Security Solution App -- a composition of ModuleJob and MlSummaryJob * that includes necessary metadata like moduleName, defaultIndexPattern, etc. */ export interface SecurityJob extends MlSummaryJob { diff --git a/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx index aac83ce650d8..aa61688f1f98 100644 --- a/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/query_bar/index.test.tsx @@ -7,14 +7,13 @@ import { mount } from 'enzyme'; import React from 'react'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; import { DEFAULT_FROM, DEFAULT_TO } from '../../../../common/constants'; import { TestProviders, mockIndexPattern } from '../../mock'; -import { createKibanaCoreStartMock } from '../../mock/kibana_core'; import { FilterManager, SearchBar } from '../../../../../../../src/plugins/data/public'; import { QueryBar, QueryBarComponentProps } from '.'; -import { createKibanaContextProviderMock } from '../../mock/kibana_react'; -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; describe('QueryBar ', () => { // We are doing that because we need to wrapped this component with redux @@ -187,13 +186,9 @@ describe('QueryBar ', () => { describe('state', () => { test('clears draftQuery when filterQueryDraft has been cleared', () => { - const KibanaWithStorageProvider = createKibanaContextProviderMock(); - const Proxy = (props: QueryBarComponentProps) => ( - - - + ); @@ -231,13 +226,9 @@ describe('QueryBar ', () => { describe('#onQueryChange', () => { test(' is the only reference that changed when filterQueryDraft props get updated', () => { - const KibanaWithStorageProvider = createKibanaContextProviderMock(); - const Proxy = (props: QueryBarComponentProps) => ( - - - + ); @@ -382,24 +373,9 @@ describe('QueryBar ', () => { describe('SavedQueryManagementComponent state', () => { test('popover should hidden when "Save current query" button was clicked', () => { - const KibanaWithStorageProvider = createKibanaContextProviderMock(); - const Proxy = (props: QueryBarComponentProps) => ( - - - + ); diff --git a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx index 0795e46c9e45..956ee4b05f9d 100644 --- a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx @@ -17,7 +17,7 @@ import { kibanaObservable, createSecuritySolutionStorageMock, } from '../../mock'; -import { createUseUiSetting$Mock } from '../../mock/kibana_react'; +import { createUseUiSetting$Mock } from '../../lib/kibana/kibana_react.mock'; import { createStore, State } from '../../store'; import { SuperDatePicker, makeMapStateToProps } from '.'; diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx index 1e93fdb93672..31318122eb56 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx @@ -18,7 +18,6 @@ import { createSecuritySolutionStorageMock, mockIndexPattern, } from '../../mock'; -import { createKibanaCoreStartMock } from '../../mock/kibana_core'; import { FilterManager } from '../../../../../../../src/plugins/data/public'; import { createStore, State } from '../../store'; @@ -29,6 +28,7 @@ import { getTimelineDefaults, } from '../../../timelines/components/manage_timeline'; import { TimelineId } from '../../../../common/types/timeline'; +import { coreMock } from '../../../../../../../src/core/public/mocks'; jest.mock('react-router-dom', () => { const original = jest.requireActual('react-router-dom'); @@ -45,7 +45,7 @@ jest.mock('../link_to'); jest.mock('../../lib/kibana'); jest.mock('../../../timelines/store/timeline/actions'); -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; const field = 'process.name'; const value = 'nice'; diff --git a/x-pack/plugins/security_solution/public/common/containers/local_storage/use_messages_storage.test.tsx b/x-pack/plugins/security_solution/public/common/containers/local_storage/use_messages_storage.test.tsx index 7085894e4a51..58f5c1a9beb2 100644 --- a/x-pack/plugins/security_solution/public/common/containers/local_storage/use_messages_storage.test.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/local_storage/use_messages_storage.test.tsx @@ -6,17 +6,13 @@ import { renderHook, act } from '@testing-library/react-hooks'; import { useKibana } from '../../lib/kibana'; -import { createUseKibanaMock } from '../../mock/kibana_react'; import { useMessagesStorage, UseMessagesStorage } from './use_messages_storage'; jest.mock('../../lib/kibana'); -const useKibanaMock = useKibana as jest.Mock; describe('useLocalStorage', () => { beforeEach(() => { - const services = { ...createUseKibanaMock()().services }; - useKibanaMock.mockImplementation(() => ({ services })); - services.storage.store.clear(); + useKibana().services.storage.clear(); }); it('should return an empty array when there is no messages', async () => { diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts index 5f4285f2747a..573ef92f7e06 100644 --- a/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts @@ -9,19 +9,21 @@ import { createKibanaContextProviderMock, createUseUiSettingMock, createUseUiSetting$Mock, - createUseKibanaMock, + createStartServicesMock, createWithKibanaMock, -} from '../../../mock/kibana_react'; +} from '../kibana_react.mock'; export const KibanaServices = { get: jest.fn(), getKibanaVersion: jest.fn(() => '8.0.0') }; -export const useKibana = jest.fn(createUseKibanaMock()); +export const useKibana = jest.fn().mockReturnValue({ services: createStartServicesMock() }); export const useUiSetting = jest.fn(createUseUiSettingMock()); export const useUiSetting$ = jest.fn(createUseUiSetting$Mock()); -export const useHttp = jest.fn(() => useKibana().services.http); +export const useHttp = jest.fn().mockReturnValue(createStartServicesMock().http); export const useTimeZone = jest.fn(); export const useDateFormat = jest.fn(); export const useBasePath = jest.fn(() => '/test/base/path'); -export const useToasts = jest.fn(() => notificationServiceMock.createStartContract().toasts); +export const useToasts = jest + .fn() + .mockReturnValue(notificationServiceMock.createStartContract().toasts); export const useCurrentUser = jest.fn(); export const withKibana = jest.fn(createWithKibanaMock()); export const KibanaContextProvider = jest.fn(createKibanaContextProviderMock()); diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts new file mode 100644 index 000000000000..c026b65853a4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/kibana_react.mock.ts @@ -0,0 +1,103 @@ +/* + * 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 { coreMock } from '../../../../../../../src/core/public/mocks'; +import { KibanaContextProvider } from '../../../../../../../src/plugins/kibana_react/public'; +import { dataPluginMock } from '../../../../../../../src/plugins/data/public/mocks'; +import { securityMock } from '../../../../../../plugins/security/public/mocks'; +import { + DEFAULT_APP_TIME_RANGE, + DEFAULT_APP_REFRESH_INTERVAL, + DEFAULT_INDEX_KEY, + DEFAULT_DATE_FORMAT, + DEFAULT_DATE_FORMAT_TZ, + DEFAULT_DARK_MODE, + DEFAULT_TIME_RANGE, + DEFAULT_REFRESH_RATE_INTERVAL, + DEFAULT_FROM, + DEFAULT_TO, + DEFAULT_INTERVAL_PAUSE, + DEFAULT_INTERVAL_VALUE, + DEFAULT_BYTES_FORMAT, + DEFAULT_INDEX_PATTERN, +} from '../../../../common/constants'; +import { StartServices } from '../../../types'; +import { createSecuritySolutionStorageMock } from '../../mock/mock_local_storage'; + +const mockUiSettings: Record = { + [DEFAULT_TIME_RANGE]: { from: 'now-15m', to: 'now', mode: 'quick' }, + [DEFAULT_REFRESH_RATE_INTERVAL]: { pause: false, value: 0 }, + [DEFAULT_APP_TIME_RANGE]: { + from: DEFAULT_FROM, + to: DEFAULT_TO, + }, + [DEFAULT_APP_REFRESH_INTERVAL]: { + pause: DEFAULT_INTERVAL_PAUSE, + value: DEFAULT_INTERVAL_VALUE, + }, + [DEFAULT_INDEX_KEY]: DEFAULT_INDEX_PATTERN, + [DEFAULT_BYTES_FORMAT]: '0,0.[0]b', + [DEFAULT_DATE_FORMAT_TZ]: 'UTC', + [DEFAULT_DATE_FORMAT]: 'MMM D, YYYY @ HH:mm:ss.SSS', + [DEFAULT_DARK_MODE]: false, +}; + +export const createUseUiSettingMock = () => (key: string, defaultValue?: unknown): unknown => { + const result = mockUiSettings[key]; + + if (typeof result != null) return result; + + if (defaultValue != null) { + return defaultValue; + } + + throw new TypeError(`Unexpected config key: ${key}`); +}; + +export const createUseUiSetting$Mock = () => { + const useUiSettingMock = createUseUiSettingMock(); + + return (key: string, defaultValue?: unknown): [unknown, () => void] | undefined => [ + useUiSettingMock(key, defaultValue), + jest.fn(), + ]; +}; + +export const createStartServicesMock = (): StartServices => { + const core = coreMock.createStart(); + core.uiSettings.get.mockImplementation(createUseUiSettingMock()); + const { storage } = createSecuritySolutionStorageMock(); + const data = dataPluginMock.createStartContract(); + const security = securityMock.createSetup(); + + const services = ({ + ...core, + data, + security, + storage, + } as unknown) as StartServices; + + return services; +}; + +export const createWithKibanaMock = () => { + const services = createStartServicesMock(); + + return (Component: unknown) => (props: unknown) => { + return React.createElement(Component as string, { ...(props as object), kibana: { services } }); + }; +}; + +export const createKibanaContextProviderMock = () => { + const services = createStartServicesMock(); + + return ({ children }: { children: React.ReactNode }) => + React.createElement(KibanaContextProvider, { services }, children); +}; diff --git a/x-pack/plugins/security_solution/public/common/mock/endpoint/app_context_render.tsx b/x-pack/plugins/security_solution/public/common/mock/endpoint/app_context_render.tsx index 1ed459521cc7..1b9e95f7d073 100644 --- a/x-pack/plugins/security_solution/public/common/mock/endpoint/app_context_render.tsx +++ b/x-pack/plugins/security_solution/public/common/mock/endpoint/app_context_render.tsx @@ -17,7 +17,7 @@ import { apolloClientObservable, kibanaObservable } from '../test_providers'; import { createStore, State } from '../../store'; import { AppRootProvider } from './app_root_provider'; import { managementMiddlewareFactory } from '../../../management/store/middleware'; -import { createKibanaContextProviderMock } from '../kibana_react'; +import { createKibanaContextProviderMock } from '../../lib/kibana/kibana_react.mock'; import { SUB_PLUGINS_REDUCER, mockGlobalState, createSecuritySolutionStorageMock } from '..'; type UiRender = (ui: React.ReactElement, options?: RenderOptions) => RenderResult; diff --git a/x-pack/plugins/security_solution/public/common/mock/index.ts b/x-pack/plugins/security_solution/public/common/mock/index.ts index 678ad4d84b58..7e076772c42f 100644 --- a/x-pack/plugins/security_solution/public/common/mock/index.ts +++ b/x-pack/plugins/security_solution/public/common/mock/index.ts @@ -16,4 +16,3 @@ export * from './test_providers'; export * from './utils'; export * from './mock_ecs'; export * from './timeline_results'; -export * from './kibana_react'; diff --git a/x-pack/plugins/security_solution/public/common/mock/kibana_core.ts b/x-pack/plugins/security_solution/public/common/mock/kibana_core.ts deleted file mode 100644 index f8eed75cf9bf..000000000000 --- a/x-pack/plugins/security_solution/public/common/mock/kibana_core.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* - * 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 { coreMock } from '../../../../../../src/core/public/mocks'; -import { dataPluginMock } from '../../../../../../src/plugins/data/public/mocks'; -import { securityMock } from '../../../../../plugins/security/public/mocks'; - -export const createKibanaCoreStartMock = () => coreMock.createStart(); -export const createKibanaPluginsStartMock = () => ({ - data: dataPluginMock.createStartContract(), - security: securityMock.createSetup(), -}); diff --git a/x-pack/plugins/security_solution/public/common/mock/kibana_react.ts b/x-pack/plugins/security_solution/public/common/mock/kibana_react.ts deleted file mode 100644 index bdb8ca85b0d7..000000000000 --- a/x-pack/plugins/security_solution/public/common/mock/kibana_react.ts +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; - -import { - DEFAULT_APP_TIME_RANGE, - DEFAULT_APP_REFRESH_INTERVAL, - DEFAULT_INDEX_KEY, - DEFAULT_DATE_FORMAT, - DEFAULT_DATE_FORMAT_TZ, - DEFAULT_DARK_MODE, - DEFAULT_TIME_RANGE, - DEFAULT_REFRESH_RATE_INTERVAL, - DEFAULT_FROM, - DEFAULT_TO, - DEFAULT_INTERVAL_PAUSE, - DEFAULT_INTERVAL_VALUE, - DEFAULT_BYTES_FORMAT, - DEFAULT_INDEX_PATTERN, -} from '../../../common/constants'; -import { createKibanaCoreStartMock, createKibanaPluginsStartMock } from './kibana_core'; -import { StartServices } from '../../types'; -import { createSecuritySolutionStorageMock } from './mock_local_storage'; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export const mockUiSettings: Record = { - [DEFAULT_TIME_RANGE]: { from: 'now-15m', to: 'now', mode: 'quick' }, - [DEFAULT_REFRESH_RATE_INTERVAL]: { pause: false, value: 0 }, - [DEFAULT_APP_TIME_RANGE]: { - from: DEFAULT_FROM, - to: DEFAULT_TO, - }, - [DEFAULT_APP_REFRESH_INTERVAL]: { - pause: DEFAULT_INTERVAL_PAUSE, - value: DEFAULT_INTERVAL_VALUE, - }, - [DEFAULT_INDEX_KEY]: DEFAULT_INDEX_PATTERN, - [DEFAULT_BYTES_FORMAT]: '0,0.[0]b', - [DEFAULT_DATE_FORMAT_TZ]: 'UTC', - [DEFAULT_DATE_FORMAT]: 'MMM D, YYYY @ HH:mm:ss.SSS', - [DEFAULT_DARK_MODE]: false, -}; - -export const createUseUiSettingMock = () => ( - key: string, - defaultValue?: T -): T => { - const result = mockUiSettings[key]; - - if (typeof result != null) return result; - - if (defaultValue != null) { - return defaultValue; - } - - throw new Error(`Unexpected config key: ${key}`); -}; - -export const createUseUiSetting$Mock = () => { - const useUiSettingMock = createUseUiSettingMock(); - - return ( - key: string, - defaultValue?: T - ): [T, () => void] | undefined => [useUiSettingMock(key, defaultValue), jest.fn()]; -}; - -export const createKibanaObservable$Mock = createKibanaCoreStartMock; - -export const createUseKibanaMock = () => { - const core = createKibanaCoreStartMock(); - const plugins = createKibanaPluginsStartMock(); - const useUiSetting = createUseUiSettingMock(); - const { storage } = createSecuritySolutionStorageMock(); - - const services = { - ...core, - ...plugins, - uiSettings: { - ...core.uiSettings, - get: useUiSetting, - }, - storage, - }; - - return () => ({ services }); -}; - -export const createStartServices = () => { - const core = createKibanaCoreStartMock(); - const plugins = createKibanaPluginsStartMock(); - - const services = ({ - ...core, - ...plugins, - } as unknown) as StartServices; - - return services; -}; - -export const createWithKibanaMock = () => { - const kibana = createUseKibanaMock()(); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (Component: any) => (props: any) => { - return React.createElement(Component, { ...props, kibana }); - }; -}; - -export const createKibanaContextProviderMock = () => { - const kibana = createUseKibanaMock()(); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return ({ services, ...rest }: any) => - React.createElement(KibanaContextProvider, { - ...rest, - services: { ...kibana.services, ...services }, - }); -}; diff --git a/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx b/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx index 010d2fac18af..9ead8171bfef 100644 --- a/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx +++ b/x-pack/plugins/security_solution/public/common/mock/test_providers.tsx @@ -19,7 +19,10 @@ import { ThemeProvider } from 'styled-components'; import { createStore, State } from '../store'; import { mockGlobalState } from './global_state'; -import { createKibanaContextProviderMock, createStartServices } from './kibana_react'; +import { + createKibanaContextProviderMock, + createStartServicesMock, +} from '../lib/kibana/kibana_react.mock'; import { FieldHook, useForm } from '../../shared_imports'; import { SUB_PLUGINS_REDUCER } from './utils'; import { createSecuritySolutionStorageMock, localStorageMock } from './mock_local_storage'; @@ -38,7 +41,7 @@ export const apolloClient = new ApolloClient({ }); export const apolloClientObservable = new BehaviorSubject(apolloClient); -export const kibanaObservable = new BehaviorSubject(createStartServices()); +export const kibanaObservable = new BehaviorSubject(createStartServicesMock()); Object.defineProperty(window, 'localStorage', { value: localStorageMock(), diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx index 0f8e0fba1e3a..291587e9f69c 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx @@ -4,4 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export const useListsConfig = jest.fn().mockReturnValue({}); +import { getUseListsConfigMock } from '../use_lists_config.mock'; + +export const useListsConfig = jest.fn(getUseListsConfigMock); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.mock.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.mock.ts new file mode 100644 index 000000000000..90f47972a3a2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.mock.ts @@ -0,0 +1,15 @@ +/* + * 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 { UseListsConfigReturn } from './use_lists_config'; + +export const getUseListsConfigMock: () => jest.Mocked = () => ({ + canManageIndex: null, + canWriteIndex: null, + enabled: true, + loading: false, + needsConfiguration: false, +}); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.test.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.test.tsx new file mode 100644 index 000000000000..a5ff29e2091b --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.test.tsx @@ -0,0 +1,86 @@ +/* + * 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 { renderHook } from '@testing-library/react-hooks'; + +import { useKibana } from '../../../../common/lib/kibana'; +import { useListsIndex } from './use_lists_index'; +import { useListsPrivileges } from './use_lists_privileges'; +import { getUseListsIndexMock } from './use_lists_index.mock'; +import { getUseListsPrivilegesMock } from './use_lists_privileges.mock'; +import { useListsConfig } from './use_lists_config'; + +jest.mock('../../../../common/lib/kibana'); +jest.mock('./use_lists_index'); +jest.mock('./use_lists_privileges'); + +describe('useListsConfig', () => { + let listsIndexMock: ReturnType; + let listsPrivilegesMock: ReturnType; + + beforeEach(() => { + listsIndexMock = getUseListsIndexMock(); + listsPrivilegesMock = getUseListsPrivilegesMock(); + (useListsIndex as jest.Mock).mockReturnValue(listsIndexMock); + (useListsPrivileges as jest.Mock).mockReturnValue(listsPrivilegesMock); + }); + + it("returns the user's write permissions", () => { + listsPrivilegesMock.canWriteIndex = false; + const { result } = renderHook(() => useListsConfig()); + expect(result.current.canWriteIndex).toEqual(false); + + listsPrivilegesMock.canWriteIndex = true; + const { result: result2 } = renderHook(() => useListsConfig()); + expect(result2.current.canWriteIndex).toEqual(true); + }); + + describe('when lists are disabled', () => { + beforeEach(() => { + useKibana().services.lists = undefined; + }); + + it('indicates that lists are not enabled, and need configuration', () => { + const { result } = renderHook(() => useListsConfig()); + expect(result.current.enabled).toEqual(false); + expect(result.current.needsConfiguration).toEqual(true); + }); + }); + + describe('when lists are enabled but indexes do not exist', () => { + beforeEach(() => { + useKibana().services.lists = {}; + listsIndexMock.indexExists = false; + }); + + it('needs configuration if the user cannot manage indexes', () => { + listsPrivilegesMock.canManageIndex = false; + + const { result } = renderHook(() => useListsConfig()); + expect(result.current.needsConfiguration).toEqual(true); + expect(listsIndexMock.createIndex).not.toHaveBeenCalled(); + }); + + it('attempts to create the indexes if the user can manage indexes', () => { + listsPrivilegesMock.canManageIndex = true; + + renderHook(() => useListsConfig()); + expect(listsIndexMock.createIndex).toHaveBeenCalled(); + }); + }); + + describe('when lists are enabled and indexes exist', () => { + beforeEach(() => { + useKibana().services.lists = {}; + listsIndexMock.indexExists = true; + }); + + it('does not need configuration', () => { + const { result } = renderHook(() => useListsConfig()); + expect(result.current.needsConfiguration).toEqual(false); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.mock.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.mock.ts new file mode 100644 index 000000000000..e2169442d80e --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.mock.ts @@ -0,0 +1,14 @@ +/* + * 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 { UseListsIndexReturn } from './use_lists_index'; + +export const getUseListsIndexMock: () => jest.Mocked = () => ({ + createIndex: jest.fn(), + indexExists: null, + error: null, + loading: false, +}); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.mock.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.mock.ts new file mode 100644 index 000000000000..4f583a72460e --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.mock.ts @@ -0,0 +1,14 @@ +/* + * 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 { UseListsPrivilegesReturn } from './use_lists_privileges'; + +export const getUseListsPrivilegesMock: () => jest.Mocked = () => ({ + isAuthenticated: null, + canManageIndex: null, + canWriteIndex: null, + loading: false, +}); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx index b07caa754aec..9f486dc11e99 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/index.test.tsx @@ -9,7 +9,6 @@ import { shallow, mount } from 'enzyme'; import { act } from 'react-dom/test-utils'; import '../../../../../common/mock/match_media'; -import { createKibanaContextProviderMock } from '../../../../../common/mock/kibana_react'; import { TestProviders } from '../../../../../common/mock'; // we don't have the types for waitFor just yet, so using "as waitFor" until when we do import { wait as waitFor } from '@testing-library/react'; @@ -182,23 +181,20 @@ describe('AllRules', () => { }); it('renders rules tab', async () => { - const KibanaContext = createKibanaContextProviderMock(); const wrapper = mount( - - - + ); @@ -211,24 +207,20 @@ describe('AllRules', () => { }); it('renders monitoring tab when monitoring tab clicked', async () => { - const KibanaContext = createKibanaContextProviderMock(); - const wrapper = mount( - - - + ); const monitoringTab = wrapper.find('[data-test-subj="allRulesTableTab-monitoring"] button'); diff --git a/x-pack/plugins/security_solution/public/overview/components/recent_cases/no_cases/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/recent_cases/no_cases/index.test.tsx index 99902a31975d..446679ae26d9 100644 --- a/x-pack/plugins/security_solution/public/overview/components/recent_cases/no_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/recent_cases/no_cases/index.test.tsx @@ -9,29 +9,19 @@ import { mount } from 'enzyme'; import { useKibana } from '../../../../common/lib/kibana'; import '../../../../common/mock/match_media'; -import { createUseKibanaMock, TestProviders } from '../../../../common/mock'; +import { TestProviders } from '../../../../common/mock'; import { NoCases } from '.'; jest.mock('../../../../common/lib/kibana'); -const useKibanaMock = useKibana as jest.Mock; - -let navigateToApp: jest.Mock; +const useKibanaMock = useKibana as jest.Mocked; describe('RecentCases', () => { + let navigateToApp: jest.Mock; + beforeEach(() => { - jest.resetAllMocks(); navigateToApp = jest.fn(); - const kibanaMock = createUseKibanaMock()(); - useKibanaMock.mockReturnValue({ - ...kibanaMock, - services: { - application: { - navigateToApp, - getUrlForApp: jest.fn(), - }, - }, - }); + useKibanaMock().services.application.navigateToApp = navigateToApp; }); it('if no cases, you should be able to create a case by clicking on the link "start a new case"', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/data_providers.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/data_providers.test.tsx index 754d7f9c47ed..d48be25b0889 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/data_providers.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/data_providers.test.tsx @@ -15,8 +15,9 @@ import { DataProvider } from './data_provider'; import { mockDataProviders } from './mock/mock_data_providers'; import { ManageGlobalTimeline, getTimelineDefaults } from '../../manage_timeline'; import { FilterManager } from '../../../../../../../../src/plugins/data/public/query/filter_manager'; -import { createKibanaCoreStartMock } from '../../../../common/mock/kibana_core'; -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +import { coreMock } from '../../../../../../../../src/core/public/mocks'; + +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; const filterManager = new FilterManager(mockUiSettingsForFilterManager); describe('DataProviders', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.test.tsx index b788f70cb2e4..3f371349aa75 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.test.tsx @@ -7,7 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; -import { createKibanaCoreStartMock } from '../../../../common/mock/kibana_core'; +import { coreMock } from '../../../../../../../../src/core/public/mocks'; import { TestProviders } from '../../../../common/mock/test_providers'; import { DroppableWrapper } from '../../../../common/components/drag_and_drop/droppable_wrapper'; import { FilterManager } from '../../../../../../../../src/plugins/data/public'; @@ -18,7 +18,7 @@ import { DELETE_CLASS_NAME, ENABLE_CLASS_NAME, EXCLUDE_CLASS_NAME } from './prov import { useMountAppended } from '../../../../common/utils/use_mount_appended'; import { ManageGlobalTimeline, getTimelineDefaults } from '../../manage_timeline'; -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; describe('Providers', () => { const isLoading: boolean = true; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx index e7b0ce7b7428..329bcf24ba7e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/header/index.test.tsx @@ -7,8 +7,8 @@ import { shallow } from 'enzyme'; import React from 'react'; +import { coreMock } from '../../../../../../../../src/core/public/mocks'; import { mockIndexPattern } from '../../../../common/mock'; -import { createKibanaCoreStartMock } from '../../../../common/mock/kibana_core'; import { TestProviders } from '../../../../common/mock/test_providers'; import { FilterManager } from '../../../../../../../../src/plugins/data/public'; import { mockDataProviders } from '../data_providers/mock/mock_data_providers'; @@ -17,7 +17,7 @@ import { useMountAppended } from '../../../../common/utils/use_mount_appended'; import { TimelineHeader } from '.'; import { TimelineStatus, TimelineType } from '../../../../../common/types/timeline'; -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; jest.mock('../../../../common/lib/kibana'); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx index 75f684c629c7..6c8fd4975c65 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx @@ -7,11 +7,11 @@ import { mount } from 'enzyme'; import React from 'react'; +import { coreMock } from '../../../../../../../../src/core/public/mocks'; import { DEFAULT_FROM, DEFAULT_TO } from '../../../../../common/constants'; import { mockBrowserFields } from '../../../../common/containers/source/mock'; import { convertKueryToElasticSearchQuery } from '../../../../common/lib/keury'; import { mockIndexPattern, TestProviders } from '../../../../common/mock'; -import { createKibanaCoreStartMock } from '../../../../common/mock/kibana_core'; import { QueryBar } from '../../../../common/components/query_bar'; import { FilterManager } from '../../../../../../../../src/plugins/data/public'; import { mockDataProviders } from '../data_providers/mock/mock_data_providers'; @@ -19,7 +19,7 @@ import { buildGlobalQuery } from '../helpers'; import { QueryBarTimeline, QueryBarTimelineComponentProps, getDataProviderFilter } from './index'; -const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; +const mockUiSettingsForFilterManager = coreMock.createStart().uiSettings; jest.mock('../../../../common/lib/kibana'); diff --git a/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.test.ts b/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.test.ts index e1bccbdff488..7a8750b279b8 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/local_storage/index.test.ts @@ -15,23 +15,16 @@ import { import { TimelineId } from '../../../../common/types/timeline'; import { mockTimelineModel, createSecuritySolutionStorageMock } from '../../../common/mock'; import { useKibana } from '../../../common/lib/kibana'; -import { createUseKibanaMock } from '../../../common/mock/kibana_react'; jest.mock('../../../common/lib/kibana'); -const useKibanaMock = useKibana as jest.Mock; +const useKibanaMock = useKibana as jest.Mocked; describe('SiemLocalStorage', () => { const { localStorage, storage } = createSecuritySolutionStorageMock(); beforeEach(() => { - jest.resetAllMocks(); - useKibanaMock.mockImplementation(() => ({ - services: { - ...createUseKibanaMock()().services, - storage, - }, - })); + useKibanaMock().services.storage = storage; localStorage.clear(); });