[Security Solution][Detections] Cleaning up mocks/tests (#74920)

* Simplify our kibana mocks

* Simpler mock factory that returns an object instead of a thunk
  * We can use mockReturnValue instead of mockImplementation to
  accomplish the same
  * Allows us to replace createStartServices mock
* Uses unknown instead of any for mocks

* Clean up our manual use of kibana mocks in tests

* Since our useKibana mock returns a consistent mock, we can modify its
return value instead of re-mocking the entire thing
* Removes unnecessary uses of clearing/resetting mocks
  * If your mocks are configured at the beginning of each test this is
  usually unnecessary.
  * I left one case of clearAllMocks in all_cases/index.test since it
  defined several mock functions that were persistent across tests, and
  it was easier than moving their definitions to a beforeEach
* Removes some unnecessary overrides that seemed due to storage
previously not being mocked

* Rename some old occurrences of SIEM

* Cross-reference similar hooks via JSDoc

There's a good chance that the consumer might want the OTHER hook, so
let's make that discoverable.

* Adds jest tests for our useListsConfig hook

* adds mocks for the hooks upon which it depends

* Add a mock for our useListsConfig hook

Leverages this mock factory in our manual mock for this hook.

* Remove unneeded eslint exception

* Move kibana_react mocks into their own .mock file

We're trying to consolidate mocks to this pattern so that they're easier
to find and reuse.

* Remove intermediate mock factory

This was only being consumed by our general createStartServicesMock.

* Replace security_solution's alias for a core mock

This is just noise/tech debt, we should use the core mock directly when
we can.

* Remove unnecessary wrapper around core mocks

Instead let's just reference the core mocks themselves.

* Remove outdated references from upstream

* More accurate mock

Throw an error of the same type if an unexpected key is used.

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
This commit is contained in:
Ryland Herrick 2020-08-24 15:38:35 -05:00 committed by GitHub
parent 4e3f47ac62
commit 0758df87fc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 430 additions and 468 deletions

View file

@ -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<CoreStart, 'http'>;
export const createKibanaCoreStartMock = (): GlobalServices => coreMock.createStart();

View file

@ -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<CoreStart, "http">' to type 'Mock<any, any>'
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<typeof coreMock.createStart>['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({});

View file

@ -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();

View file

@ -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();

View file

@ -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();

View file

@ -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();

View file

@ -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<typeof useKibana>;
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(
<TestProviders>

View file

@ -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() },
},
};

View file

@ -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<typeof useKibana>;
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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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(<ConfigureCases userCanCrud />, { 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);
});

View file

@ -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<typeof useKibana>;
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 () => {

View file

@ -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';

View file

@ -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<ReturnType<
@ -49,10 +46,6 @@ describe('When the add exception modal is opened', () => {
.spyOn(builder, 'ExceptionBuilderComponent')
.mockReturnValue(<></>);
const kibanaMock = createUseKibanaMock()();
useKibanaMock.mockImplementation(() => ({
...kibanaMock,
}));
(useAddOrUpdateException as jest.Mock).mockImplementation(() => [
{ isLoading: false },
jest.fn(),

View file

@ -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',

View file

@ -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');

View file

@ -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', () => {

View file

@ -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<MlSummaryJob[]>([]);

View file

@ -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<SecurityJob[]>([]);
const [loading, setLoading] = useState(true);
const mlCapabilities = useMlCapabilities();
const [siemDefaultIndex] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY);
const [securitySolutionDefaultIndex] = useUiSetting$<string[]>(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 };
};

View file

@ -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 {

View file

@ -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) => (
<TestProviders>
<KibanaWithStorageProvider services={{ storage: { get: jest.fn() } }}>
<QueryBar {...props} />
</KibanaWithStorageProvider>
<QueryBar {...props} />
</TestProviders>
);
@ -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) => (
<TestProviders>
<KibanaWithStorageProvider services={{ storage: { get: jest.fn() } }}>
<QueryBar {...props} />
</KibanaWithStorageProvider>
<QueryBar {...props} />
</TestProviders>
);
@ -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) => (
<TestProviders>
<KibanaWithStorageProvider
services={{
data: {
query: {
savedQueries: {
findSavedQueries: jest.fn().mockResolvedValue({ total: 0, queries: [] }),
getAllSavedQueries: jest.fn().mockResolvedValue([]),
},
},
},
}}
>
<QueryBar {...props} />
</KibanaWithStorageProvider>
<QueryBar {...props} />
</TestProviders>
);

View file

@ -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 '.';

View file

@ -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';

View file

@ -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 () => {

View file

@ -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());

View file

@ -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<string, unknown> = {
[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);
};

View file

@ -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;

View file

@ -16,4 +16,3 @@ export * from './test_providers';
export * from './utils';
export * from './mock_ecs';
export * from './timeline_results';
export * from './kibana_react';

View file

@ -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(),
});

View file

@ -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<string, any> = {
[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 = () => <T extends unknown = string>(
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 <T extends unknown = string>(
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 },
});
};

View file

@ -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(),

View file

@ -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);

View file

@ -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<UseListsConfigReturn> = () => ({
canManageIndex: null,
canWriteIndex: null,
enabled: true,
loading: false,
needsConfiguration: false,
});

View file

@ -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<typeof getUseListsIndexMock>;
let listsPrivilegesMock: ReturnType<typeof getUseListsPrivilegesMock>;
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);
});
});
});

View file

@ -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<UseListsIndexReturn> = () => ({
createIndex: jest.fn(),
indexExists: null,
error: null,
loading: false,
});

View file

@ -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<UseListsPrivilegesReturn> = () => ({
isAuthenticated: null,
canManageIndex: null,
canWriteIndex: null,
loading: false,
});

View file

@ -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(
<TestProviders>
<KibanaContext services={{ storage: { get: jest.fn() } }}>
<AllRules
createPrePackagedRules={jest.fn()}
hasNoPermissions={false}
loading={false}
loadingCreatePrePackagedRules={false}
refetchPrePackagedRulesStatus={jest.fn()}
rulesCustomInstalled={1}
rulesInstalled={0}
rulesNotInstalled={0}
rulesNotUpdated={0}
setRefreshRulesData={jest.fn()}
/>
</KibanaContext>
<AllRules
createPrePackagedRules={jest.fn()}
hasNoPermissions={false}
loading={false}
loadingCreatePrePackagedRules={false}
refetchPrePackagedRulesStatus={jest.fn()}
rulesCustomInstalled={1}
rulesInstalled={0}
rulesNotInstalled={0}
rulesNotUpdated={0}
setRefreshRulesData={jest.fn()}
/>
</TestProviders>
);
@ -211,24 +207,20 @@ describe('AllRules', () => {
});
it('renders monitoring tab when monitoring tab clicked', async () => {
const KibanaContext = createKibanaContextProviderMock();
const wrapper = mount(
<TestProviders>
<KibanaContext services={{ storage: { get: jest.fn() } }}>
<AllRules
createPrePackagedRules={jest.fn()}
hasNoPermissions={false}
loading={false}
loadingCreatePrePackagedRules={false}
refetchPrePackagedRulesStatus={jest.fn()}
rulesCustomInstalled={1}
rulesInstalled={0}
rulesNotInstalled={0}
rulesNotUpdated={0}
setRefreshRulesData={jest.fn()}
/>
</KibanaContext>
<AllRules
createPrePackagedRules={jest.fn()}
hasNoPermissions={false}
loading={false}
loadingCreatePrePackagedRules={false}
refetchPrePackagedRulesStatus={jest.fn()}
rulesCustomInstalled={1}
rulesInstalled={0}
rulesNotInstalled={0}
rulesNotUpdated={0}
setRefreshRulesData={jest.fn()}
/>
</TestProviders>
);
const monitoringTab = wrapper.find('[data-test-subj="allRulesTableTab-monitoring"] button');

View file

@ -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<typeof useKibana>;
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"', () => {

View file

@ -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', () => {

View file

@ -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;

View file

@ -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');

View file

@ -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');

View file

@ -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<typeof useKibana>;
describe('SiemLocalStorage', () => {
const { localStorage, storage } = createSecuritySolutionStorageMock();
beforeEach(() => {
jest.resetAllMocks();
useKibanaMock.mockImplementation(() => ({
services: {
...createUseKibanaMock()().services,
storage,
},
}));
useKibanaMock().services.storage = storage;
localStorage.clear();
});