diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx index 8176d3fcbbca2..6e246380e7049 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx @@ -5,9 +5,7 @@ * 2.0. */ -import React from 'react'; import { of } from 'rxjs'; -import { ComponentType } from 'enzyme'; import { LocationDescriptorObject } from 'history'; import { @@ -17,7 +15,6 @@ import { httpServiceMock, scopedHistoryMock, } from '../../../../../../src/core/public/mocks'; -import { AppContextProvider } from '../../../public/application/app_context'; import { AppDeps } from '../../../public/application/app'; import { LicenseStatus } from '../../../common/types/license_status'; @@ -52,11 +49,3 @@ export const mockContextValue: AppDeps = { history, getUrlForApp: jest.fn(), }; - -export const withAppContext = (Component: ComponentType) => (props: any) => { - return ( - - - - ); -}; diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts deleted file mode 100644 index dce7213297388..0000000000000 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts +++ /dev/null @@ -1,10 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -export const wrapBodyResponse = (obj: object) => JSON.stringify({ body: JSON.stringify(obj) }); - -export const unwrapBodyResponse = (string: string) => JSON.parse(JSON.parse(string).body); diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts index e98cd66a25684..31c82cc33cd59 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts @@ -5,123 +5,115 @@ * 2.0. */ -import sinon, { SinonFakeServer } from 'sinon'; +import { httpServiceMock } from '../../../../../../src/core/public/mocks'; import { ROUTES } from '../../../common/constants'; const { API_ROOT } = ROUTES; type HttpResponse = Record | any[]; - -const mockResponse = (defaultResponse: HttpResponse, response: HttpResponse) => [ - 200, - { 'Content-Type': 'application/json' }, - JSON.stringify({ ...defaultResponse, ...response }), -]; +type HttpMethod = 'GET' | 'PUT' | 'POST'; +export interface ResponseError { + statusCode: number; + message: string | Error; +} // Register helpers to mock HTTP Requests -const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { - const setLoadWatchesResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watches: [] }; - - server.respondWith('GET', `${API_ROOT}/watches`, mockResponse(defaultResponse, response)); - }; - - const setLoadWatchResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watch: {} }; - server.respondWith('GET', `${API_ROOT}/watch/:id`, mockResponse(defaultResponse, response)); - }; - - const setLoadWatchHistoryResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchHistoryItems: [] }; - server.respondWith( - 'GET', - `${API_ROOT}/watch/:id/history`, - mockResponse(defaultResponse, response) - ); - }; - - const setLoadWatchHistoryItemResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchHistoryItem: {} }; - server.respondWith('GET', `${API_ROOT}/history/:id`, mockResponse(defaultResponse, response)); - }; - - const setDeleteWatchResponse = (response?: HttpResponse, error?: any) => { - const status = error ? error.status || 400 : 200; - const body = error ? JSON.stringify(error.body) : JSON.stringify(response); - - server.respondWith('POST', `${API_ROOT}/watches/delete`, [ - status, - { 'Content-Type': 'application/json' }, - body, - ]); - }; - - const setSaveWatchResponse = (id: string, response?: HttpResponse, error?: any) => { - const status = error ? error.status || 400 : 200; - const body = error ? JSON.stringify(error.body) : JSON.stringify(response); - - server.respondWith('PUT', `${API_ROOT}/watch/${id}`, [ - status, - { 'Content-Type': 'application/json' }, - body, - ]); - }; - - const setLoadExecutionResultResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchHistoryItem: {} }; - server.respondWith('PUT', `${API_ROOT}/watch/execute`, mockResponse(defaultResponse, response)); - }; - - const setLoadMatchingIndicesResponse = (response: HttpResponse = {}) => { - const defaultResponse = { indices: [] }; - server.respondWith('POST', `${API_ROOT}/indices`, mockResponse(defaultResponse, response)); - }; - - const setLoadEsFieldsResponse = (response: HttpResponse = {}) => { - const defaultResponse = { fields: [] }; - server.respondWith('POST', `${API_ROOT}/fields`, mockResponse(defaultResponse, response)); - }; - - const setLoadSettingsResponse = (response: HttpResponse = {}) => { - const defaultResponse = { action_types: {} }; - server.respondWith('GET', `${API_ROOT}/settings`, mockResponse(defaultResponse, response)); - }; - - const setLoadWatchVisualizeResponse = (response: HttpResponse = {}) => { - const defaultResponse = { visualizeData: {} }; - server.respondWith( - 'POST', - `${API_ROOT}/watch/visualize`, - mockResponse(defaultResponse, response) - ); - }; - - const setDeactivateWatchResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchStatus: {} }; - server.respondWith( +const registerHttpRequestMockHelpers = ( + httpSetup: ReturnType +) => { + const mockResponses = new Map>>( + ['GET', 'PUT', 'POST'].map( + (method) => [method, new Map()] as [HttpMethod, Map>] + ) + ); + + const mockMethodImplementation = (method: HttpMethod, path: string) => + mockResponses.get(method)?.get(path) ?? Promise.resolve({}); + + httpSetup.get.mockImplementation((path) => + mockMethodImplementation('GET', path as unknown as string) + ); + httpSetup.post.mockImplementation((path) => + mockMethodImplementation('POST', path as unknown as string) + ); + httpSetup.put.mockImplementation((path) => + mockMethodImplementation('PUT', path as unknown as string) + ); + + const mockResponse = (method: HttpMethod, path: string, response?: unknown, error?: unknown) => { + const defuse = (promise: Promise) => { + promise.catch(() => {}); + return promise; + }; + + return mockResponses + .get(method)! + .set(path, error ? defuse(Promise.reject(error)) : Promise.resolve(response)); + }; + + const setLoadWatchesResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/watches`, response, error); + + const setLoadWatchResponse = (watchId: string, response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/watch/${watchId}`, response, error); + + const setLoadWatchHistoryResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('GET', `${API_ROOT}/watch/${watchId}/history`, response, error); + + const setLoadWatchHistoryItemResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('GET', `${API_ROOT}/watch/history/${watchId}`, response, error); + + const setDeleteWatchResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('POST', `${API_ROOT}/watches/delete`, response, error); + + const setSaveWatchResponse = (watchId: string, response?: HttpResponse, error?: ResponseError) => + mockResponse('PUT', `${API_ROOT}/watch/${watchId}`, response, error); + + const setLoadExecutionResultResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('PUT', `${API_ROOT}/watch/execute`, response, error); + + const setLoadMatchingIndicesResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('PUT', `${API_ROOT}/indices`, response, error); + + const setLoadEsFieldsResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('POST', `${API_ROOT}/fields`, response, error); + + const setLoadSettingsResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/settings`, response, error); + + const setLoadWatchVisualizeResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('POST', `${API_ROOT}/watch/visualize`, response, error); + + const setDeactivateWatchResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/deactivate`, response, error); + + const setActivateWatchResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/activate`, response, error); + + const setAcknowledgeWatchResponse = ( + watchId: string, + actionId: string, + response?: HttpResponse, + error?: ResponseError + ) => + mockResponse( 'PUT', - `${API_ROOT}/watch/:id/deactivate`, - mockResponse(defaultResponse, response) + `${API_ROOT}/watch/${watchId}/action/${actionId}/acknowledge`, + response, + error ); - }; - - const setActivateWatchResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchStatus: {} }; - server.respondWith( - 'PUT', - `${API_ROOT}/watch/:id/activate`, - mockResponse(defaultResponse, response) - ); - }; - - const setAcknowledgeWatchResponse = (response: HttpResponse = {}) => { - const defaultResponse = { watchStatus: {} }; - server.respondWith( - 'PUT', - `${API_ROOT}/watch/:id/action/:actionId/acknowledge`, - mockResponse(defaultResponse, response) - ); - }; return { setLoadWatchesResponse, @@ -142,18 +134,11 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => { }; export const init = () => { - const server = sinon.fakeServer.create(); - server.respondImmediately = true; - - // Define default response for unhandled requests. - // We make requests to APIs which don't impact the component under test, e.g. UI metric telemetry, - // and we can mock them all with a 200 instead of mocking each one individually. - server.respondWith([200, {}, 'DefaultResponse']); - - const httpRequestsMockHelpers = registerHttpRequestMockHelpers(server); + const httpSetup = httpServiceMock.createSetupContract(); + const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup); return { - server, + httpSetup, httpRequestsMockHelpers, }; }; diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts index 37fe71d143988..91a7b09b13c36 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts @@ -13,7 +13,6 @@ import { setup as watchEditSetup } from './watch_edit.helpers'; export type { TestBed } from '@kbn/test/jest'; export { getRandomString, findTestSubject } from '@kbn/test/jest'; -export { wrapBodyResponse, unwrapBodyResponse } from './body_response'; export { setupEnvironment } from './setup_environment'; export const pageHelpers = { diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts deleted file mode 100644 index 5ba0387d21ba7..0000000000000 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts +++ /dev/null @@ -1,42 +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 - * 2.0; you may not use this file except in compliance with the Elastic License - * 2.0. - */ - -import axios from 'axios'; -import axiosXhrAdapter from 'axios/lib/adapters/xhr'; - -import { init as initHttpRequests } from './http_requests'; -import { setHttpClient, setSavedObjectsClient } from '../../../public/application/lib/api'; - -const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -mockHttpClient.interceptors.response.use( - (res) => { - return res.data; - }, - (rej) => { - return Promise.reject(rej); - } -); - -const mockSavedObjectsClient = () => { - return { - find: (_params?: any) => {}, - }; -}; - -export const setupEnvironment = () => { - const { server, httpRequestsMockHelpers } = initHttpRequests(); - - // @ts-ignore - setHttpClient(mockHttpClient); - - setSavedObjectsClient(mockSavedObjectsClient() as any); - - return { - server, - httpRequestsMockHelpers, - }; -}; diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx new file mode 100644 index 0000000000000..63822efa07f63 --- /dev/null +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0; you may not use this file except in compliance with the Elastic License + * 2.0. + */ + +import React from 'react'; +import { HttpSetup } from 'src/core/public'; + +import { init as initHttpRequests } from './http_requests'; +import { mockContextValue } from './app_context.mock'; +import { AppContextProvider } from '../../../public/application/app_context'; +import { setHttpClient, setSavedObjectsClient } from '../../../public/application/lib/api'; + +const mockSavedObjectsClient = () => { + return { + find: (_params?: any) => ({ + savedObjects: [], + }), + }; +}; + +export const WithAppDependencies = + (Component: any, httpSetup: HttpSetup) => (props: Record) => { + setHttpClient(httpSetup); + + return ( + + + + ); + }; + +export const setupEnvironment = () => { + setSavedObjectsClient(mockSavedObjectsClient() as any); + + return initHttpRequests(); +}; diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts index a276b717bc544..cb41ab8ed26c8 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts @@ -6,10 +6,12 @@ */ import { registerTestBed, TestBed, AsyncTestBedConfig } from '@kbn/test/jest'; +import { HttpSetup } from 'src/core/public'; + import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { withAppContext } from './app_context.mock'; +import { WithAppDependencies } from './setup_environment'; const testBedConfig: AsyncTestBedConfig = { memoryRouter: { @@ -20,8 +22,6 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); - export interface WatchCreateJsonTestBed extends TestBed { actions: { selectTab: (tab: 'edit' | 'simulate') => void; @@ -30,7 +30,8 @@ export interface WatchCreateJsonTestBed extends TestBed => { +export const setup = async (httpSetup: HttpSetup): Promise => { + const initTestBed = registerTestBed(WithAppDependencies(WatchEdit, httpSetup), testBedConfig); const testBed = await initTestBed(); /** diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts index 320f88eef2651..f7bf0c6847825 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts @@ -6,10 +6,12 @@ */ import { registerTestBed, TestBed, AsyncTestBedConfig } from '@kbn/test/jest'; +import { HttpSetup } from 'src/core/public'; + import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES, WATCH_TYPES } from '../../../common/constants'; -import { withAppContext } from './app_context.mock'; +import { WithAppDependencies } from './setup_environment'; const testBedConfig: AsyncTestBedConfig = { memoryRouter: { @@ -20,8 +22,6 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); - export interface WatchCreateThresholdTestBed extends TestBed { actions: { clickSubmitButton: () => void; @@ -33,7 +33,8 @@ export interface WatchCreateThresholdTestBed extends TestBed => { +export const setup = async (httpSetup: HttpSetup): Promise => { + const initTestBed = registerTestBed(WithAppDependencies(WatchEdit, httpSetup), testBedConfig); const testBed = await initTestBed(); /** diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts index 15489fa0a864d..9a85041023949 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts @@ -6,11 +6,13 @@ */ import { registerTestBed, TestBed, AsyncTestBedConfig } from '@kbn/test/jest'; +import { HttpSetup } from 'src/core/public'; + import { WatchEdit } from '../../../public/application/sections/watch_edit/components/watch_edit'; import { registerRouter } from '../../../public/application/lib/navigation'; import { ROUTES } from '../../../common/constants'; import { WATCH_ID } from './jest_constants'; -import { withAppContext } from './app_context.mock'; +import { WithAppDependencies } from './setup_environment'; const testBedConfig: AsyncTestBedConfig = { memoryRouter: { @@ -21,15 +23,14 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig); - export interface WatchEditTestBed extends TestBed { actions: { clickSubmitButton: () => void; }; } -export const setup = async (): Promise => { +export const setup = async (httpSetup: HttpSetup): Promise => { + const initTestBed = registerTestBed(WithAppDependencies(WatchEdit, httpSetup), testBedConfig); const testBed = await initTestBed(); /** diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts index d048a55422f6e..d14de58c546f8 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts @@ -8,9 +8,11 @@ import { act } from 'react-dom/test-utils'; import { registerTestBed, findTestSubject, TestBed, AsyncTestBedConfig } from '@kbn/test/jest'; +import { HttpSetup } from 'src/core/public'; + import { WatchList } from '../../../public/application/sections/watch_list/components/watch_list'; import { ROUTES, REFRESH_INTERVALS } from '../../../common/constants'; -import { withAppContext } from './app_context.mock'; +import { WithAppDependencies } from './setup_environment'; const testBedConfig: AsyncTestBedConfig = { memoryRouter: { @@ -19,8 +21,6 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchList), testBedConfig); - export interface WatchListTestBed extends TestBed { actions: { selectWatchAt: (index: number) => void; @@ -30,7 +30,8 @@ export interface WatchListTestBed extends TestBed { }; } -export const setup = async (): Promise => { +export const setup = async (httpSetup: HttpSetup): Promise => { + const initTestBed = registerTestBed(WithAppDependencies(WatchList, httpSetup), testBedConfig); const testBed = await initTestBed(); /** diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts index 0578f9f1092a1..3a1bb451859bd 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts @@ -7,22 +7,24 @@ import { act } from 'react-dom/test-utils'; +import { HttpSetup } from 'src/core/public'; import { registerTestBed, findTestSubject, TestBed, AsyncTestBedConfig } from '@kbn/test/jest'; + +import { registerRouter } from '../../../public/application/lib/navigation'; import { WatchStatus } from '../../../public/application/sections/watch_status/components/watch_status'; import { ROUTES } from '../../../common/constants'; import { WATCH_ID } from './jest_constants'; -import { withAppContext } from './app_context.mock'; +import { WithAppDependencies } from './setup_environment'; const testBedConfig: AsyncTestBedConfig = { memoryRouter: { + onRouter: (router) => registerRouter(router), initialEntries: [`${ROUTES.API_ROOT}/watches/watch/${WATCH_ID}/status`], componentRoutePath: `${ROUTES.API_ROOT}/watches/watch/:id/status`, }, doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchStatus), testBedConfig); - export interface WatchStatusTestBed extends TestBed { actions: { selectTab: (tab: 'execution history' | 'action statuses') => void; @@ -33,7 +35,8 @@ export interface WatchStatusTestBed extends TestBed { }; } -export const setup = async (): Promise => { +export const setup = async (httpSetup: HttpSetup): Promise => { + const initTestBed = registerTestBed(WithAppDependencies(WatchStatus, httpSetup), testBedConfig); const testBed = await initTestBed(); /** diff --git a/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts index f9ea51a80ae76..fc518bcab882b 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_json.test.ts @@ -8,15 +8,16 @@ import { act } from 'react-dom/test-utils'; import { getExecuteDetails } from '../../__fixtures__'; +import { API_BASE_PATH } from '../../common/constants'; import { defaultWatch } from '../../public/application/models/watch'; -import { setupEnvironment, pageHelpers, wrapBodyResponse } from './helpers'; +import { setupEnvironment, pageHelpers } from './helpers'; import { WatchCreateJsonTestBed } from './helpers/watch_create_json.helpers'; import { WATCH } from './helpers/jest_constants'; const { setup } = pageHelpers.watchCreateJson; describe(' create route', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchCreateJsonTestBed; beforeAll(() => { @@ -25,12 +26,11 @@ describe(' create route', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('on component mount', () => { beforeEach(async () => { - testBed = await setup(); + testBed = await setup(httpSetup); testBed.component.update(); }); @@ -94,31 +94,32 @@ describe(' create route', () => { actions.clickSubmitButton(); }); - const latestRequest = server.requests[server.requests.length - 1]; - const DEFAULT_LOGGING_ACTION_ID = 'logging_1'; const DEFAULT_LOGGING_ACTION_TYPE = 'logging'; const DEFAULT_LOGGING_ACTION_TEXT = 'There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10.'; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - id: watch.id, - name: watch.name, - type: watch.type, - isNew: true, - isActive: true, - actions: [ - { - id: DEFAULT_LOGGING_ACTION_ID, - type: DEFAULT_LOGGING_ACTION_TYPE, - text: DEFAULT_LOGGING_ACTION_TEXT, - [DEFAULT_LOGGING_ACTION_TYPE]: { + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${watch.id}`, + expect.objectContaining({ + body: JSON.stringify({ + id: watch.id, + name: watch.name, + type: watch.type, + isNew: true, + isActive: true, + actions: [ + { + id: DEFAULT_LOGGING_ACTION_ID, + type: DEFAULT_LOGGING_ACTION_TYPE, text: DEFAULT_LOGGING_ACTION_TEXT, + [DEFAULT_LOGGING_ACTION_TYPE]: { + text: DEFAULT_LOGGING_ACTION_TEXT, + }, }, - }, - ], - watch: defaultWatch, + ], + watch: defaultWatch, + }), }) ); }); @@ -131,12 +132,13 @@ describe(' create route', () => { form.setInputValue('idInput', watch.id); const error = { - status: 400, + statusCode: 400, error: 'Bad request', message: 'Watch payload is invalid', + response: {}, }; - httpRequestsMockHelpers.setSaveWatchResponse(watch.id, undefined, { body: error }); + httpRequestsMockHelpers.setSaveWatchResponse(watch.id, undefined, error); await act(async () => { actions.clickSubmitButton(); @@ -169,8 +171,6 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - const latestRequest = server.requests[server.requests.length - 1]; - const actionModes = Object.keys(defaultWatch.actions).reduce( (actionAccum: any, action) => { actionAccum[action] = 'simulate'; @@ -188,12 +188,15 @@ describe(' create route', () => { watch: defaultWatch, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes, + }), + watch: executedWatch, }), - watch: executedWatch, }) ); }); @@ -230,8 +233,6 @@ describe(' create route', () => { }); component.update(); - const latestRequest = server.requests[server.requests.length - 1]; - const actionModes = Object.keys(defaultWatch.actions).reduce( (actionAccum: any, action) => { actionAccum[action] = ACTION_MODE; @@ -252,19 +253,23 @@ describe(' create route', () => { const triggeredTime = `now+${TRIGGERED_TIME}s`; const scheduledTime = `now+${SCHEDULED_TIME}s`; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - triggerData: { - triggeredTime, - scheduledTime, - }, - ignoreCondition: IGNORE_CONDITION, - actionModes, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + triggerData: { + triggeredTime, + scheduledTime, + }, + ignoreCondition: IGNORE_CONDITION, + actionModes, + }), + watch: executedWatch, }), - watch: executedWatch, }) ); + expect(exists('simulateResultsFlyout')).toBe(true); expect(find('simulateResultsFlyoutTitle').text()).toEqual('Simulation results'); }); diff --git a/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx index 481f59093d7dc..2a70b4852c77a 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx @@ -7,12 +7,12 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; -import axiosXhrAdapter from 'axios/lib/adapters/xhr'; -import axios from 'axios'; +import { HttpFetchOptionsWithPath } from 'kibana/public'; +import { WATCH_ID } from './helpers/jest_constants'; import { getExecuteDetails } from '../../__fixtures__'; -import { WATCH_TYPES } from '../../common/constants'; -import { setupEnvironment, pageHelpers, wrapBodyResponse, unwrapBodyResponse } from './helpers'; +import { WATCH_TYPES, API_BASE_PATH } from '../../common/constants'; +import { setupEnvironment, pageHelpers } from './helpers'; import { WatchCreateThresholdTestBed } from './helpers/watch_create_threshold.helpers'; const WATCH_NAME = 'my_test_watch'; @@ -23,6 +23,18 @@ const MATCH_INDICES = ['index1']; const ES_FIELDS = [{ name: '@timestamp', type: 'date' }]; +// Since watchID's are dynamically created, we have to mock +// the function that generates them in order to be able to match +// against it. +jest.mock('uuid/v4', () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { WATCH_ID: watchId } = require('./helpers/jest_constants'); + + return function () { + return watchId; + }; +}); + const SETTINGS = { action_types: { email: { enabled: true }, @@ -36,32 +48,15 @@ const SETTINGS = { }; const WATCH_VISUALIZE_DATA = { - count: [ - [1559404800000, 14], - [1559448000000, 196], - [1559491200000, 44], - ], + visualizeData: { + count: [ + [1559404800000, 14], + [1559448000000, 196], + [1559491200000, 44], + ], + }, }; -const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); - -jest.mock('../../public/application/lib/api', () => { - const original = jest.requireActual('../../public/application/lib/api'); - - return { - ...original, - loadIndexPatterns: async () => { - const INDEX_PATTERNS = [ - { attributes: { title: 'index1' } }, - { attributes: { title: 'index2' } }, - { attributes: { title: 'index3' } }, - ]; - return await INDEX_PATTERNS; - }, - getHttpClient: () => mockHttpClient, - }; -}); - jest.mock('@elastic/eui', () => { const original = jest.requireActual('@elastic/eui'); @@ -85,7 +80,7 @@ jest.mock('@elastic/eui', () => { const { setup } = pageHelpers.watchCreateThreshold; describe(' create route', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchCreateThresholdTestBed; beforeAll(() => { @@ -94,14 +89,15 @@ describe(' create route', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('on component mount', () => { beforeEach(async () => { - testBed = await setup(); - const { component } = testBed; - component.update(); + await act(async () => { + testBed = await setup(httpSetup); + }); + + testBed.component.update(); }); test('should set the correct page title', () => { @@ -167,6 +163,7 @@ describe(' create route', () => { find('indicesComboBox').simulate('change', [{ label: 'index1', value: 'index1' }]); // Using mocked EuiComboBox form.setInputValue('watchTimeFieldSelect', '@timestamp'); }); + component.update(); expect(find('saveWatchButton').props().disabled).toBe(false); @@ -255,11 +252,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -288,16 +282,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - logging_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + logging_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -317,11 +314,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -349,16 +343,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - index_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + index_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -379,11 +376,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -414,16 +408,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - slack_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + slack_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -451,11 +448,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -490,16 +484,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - email_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + email_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -543,11 +540,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -584,16 +578,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - webhook_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + webhook_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -631,11 +628,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -674,16 +668,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - jira_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + jira_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -711,11 +708,8 @@ describe(' create route', () => { actions.clickSimulateButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).watch.id, // watch ID is created dynamically + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -744,16 +738,19 @@ describe(' create route', () => { threshold: 1000, }; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - executeDetails: getExecuteDetails({ - actionModes: { - pagerduty_1: 'force_execute', - }, - ignoreCondition: true, - recordExecution: false, + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/execute`, + expect.objectContaining({ + body: JSON.stringify({ + executeDetails: getExecuteDetails({ + actionModes: { + pagerduty_1: 'force_execute', + }, + ignoreCondition: true, + recordExecution: false, + }), + watch: thresholdWatch, }), - watch: thresholdWatch, }) ); }); @@ -771,17 +768,14 @@ describe(' create route', () => { }); component.update(); - const latestReqToGetVisualizeData = server.requests.find( - (req) => req.method === 'POST' && req.url === '/api/watcher/watch/visualize' - ); - if (!latestReqToGetVisualizeData) { - throw new Error(`No request found to fetch visualize data.`); - } - - const requestBody = unwrapBodyResponse(latestReqToGetVisualizeData.requestBody); + const lastReq: HttpFetchOptionsWithPath[] = httpSetup.post.mock.calls.pop() || []; + const [requestUrl, watchBody] = lastReq; + // Options contains two dinamically computed timestamps, so it's simpler to just ignore those fields. + const { options, ...body } = JSON.parse((watchBody as Record).body).watch; - expect(requestBody.watch).toEqual({ - id: requestBody.watch.id, // id is dynamic + expect(requestUrl).toBe(`${API_BASE_PATH}/watch/visualize`); + expect(body).toEqual({ + id: WATCH_ID, name: 'my_test_watch', type: 'threshold', isNew: true, @@ -800,8 +794,6 @@ describe(' create route', () => { hasTermsAgg: false, threshold: 1000, }); - - expect(requestBody.options.interval).toBeDefined(); }); }); @@ -821,31 +813,31 @@ describe(' create route', () => { actions.clickSubmitButton(); }); - // Verify request - const latestRequest = server.requests[server.requests.length - 1]; - - const thresholdWatch = { - id: unwrapBodyResponse(latestRequest.requestBody).id, // watch ID is created dynamically - name: WATCH_NAME, - type: WATCH_TYPES.THRESHOLD, - isNew: true, - isActive: true, - actions: [], - index: MATCH_INDICES, - timeField: WATCH_TIME_FIELD, - triggerIntervalSize: 1, - triggerIntervalUnit: 'm', - aggType: 'count', - termSize: 5, - termOrder: 'desc', - thresholdComparator: '>', - timeWindowSize: 5, - timeWindowUnit: 'm', - hasTermsAgg: false, - threshold: 1000, - }; - - expect(latestRequest.requestBody).toEqual(wrapBodyResponse(thresholdWatch)); + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${WATCH_ID}`, + expect.objectContaining({ + body: JSON.stringify({ + id: WATCH_ID, + name: WATCH_NAME, + type: WATCH_TYPES.THRESHOLD, + isNew: true, + isActive: true, + actions: [], + index: MATCH_INDICES, + timeField: WATCH_TIME_FIELD, + triggerIntervalSize: 1, + triggerIntervalUnit: 'm', + aggType: 'count', + termSize: 5, + termOrder: 'desc', + thresholdComparator: '>', + timeWindowSize: 5, + timeWindowUnit: 'm', + hasTermsAgg: false, + threshold: 1000, + }), + }) + ); }); }); }); diff --git a/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts index 1188cc8469a58..8b0ee0189695b 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts @@ -6,39 +6,18 @@ */ import { act } from 'react-dom/test-utils'; -import axiosXhrAdapter from 'axios/lib/adapters/xhr'; -import axios from 'axios'; -import { getRandomString } from '@kbn/test/jest'; import { getWatch } from '../../__fixtures__'; import { defaultWatch } from '../../public/application/models/watch'; -import { setupEnvironment, pageHelpers, wrapBodyResponse } from './helpers'; +import { setupEnvironment, pageHelpers } from './helpers'; import { WatchEditTestBed } from './helpers/watch_edit.helpers'; -import { WATCH } from './helpers/jest_constants'; - -const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); - -jest.mock('../../public/application/lib/api', () => { - const original = jest.requireActual('../../public/application/lib/api'); - - return { - ...original, - loadIndexPatterns: async () => { - const INDEX_PATTERNS = [ - { attributes: { title: 'index1' } }, - { attributes: { title: 'index2' } }, - { attributes: { title: 'index3' } }, - ]; - return await INDEX_PATTERNS; - }, - getHttpClient: () => mockHttpClient, - }; -}); +import { WATCH, WATCH_ID } from './helpers/jest_constants'; +import { API_BASE_PATH } from '../../common/constants'; const { setup } = pageHelpers.watchEdit; describe('', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchEditTestBed; beforeAll(() => { @@ -47,14 +26,13 @@ describe('', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('Advanced watch', () => { beforeEach(async () => { - httpRequestsMockHelpers.setLoadWatchResponse(WATCH); + httpRequestsMockHelpers.setLoadWatchResponse(WATCH_ID, WATCH); - testBed = await setup(); + testBed = await setup(httpSetup); testBed.component.update(); }); @@ -90,31 +68,32 @@ describe('', () => { actions.clickSubmitButton(); }); - const latestRequest = server.requests[server.requests.length - 1]; - const DEFAULT_LOGGING_ACTION_ID = 'logging_1'; const DEFAULT_LOGGING_ACTION_TYPE = 'logging'; const DEFAULT_LOGGING_ACTION_TEXT = 'There are {{ctx.payload.hits.total}} documents in your index. Threshold is 10.'; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - id: watch.id, - name: EDITED_WATCH_NAME, - type: watch.type, - isNew: false, - isActive: true, - actions: [ - { - id: DEFAULT_LOGGING_ACTION_ID, - type: DEFAULT_LOGGING_ACTION_TYPE, - text: DEFAULT_LOGGING_ACTION_TEXT, - [DEFAULT_LOGGING_ACTION_TYPE]: { + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${watch.id}`, + expect.objectContaining({ + body: JSON.stringify({ + id: watch.id, + name: EDITED_WATCH_NAME, + type: watch.type, + isNew: false, + isActive: true, + actions: [ + { + id: DEFAULT_LOGGING_ACTION_ID, + type: DEFAULT_LOGGING_ACTION_TYPE, text: DEFAULT_LOGGING_ACTION_TEXT, + [DEFAULT_LOGGING_ACTION_TYPE]: { + text: DEFAULT_LOGGING_ACTION_TEXT, + }, }, - }, - ], - watch: defaultWatch, + ], + watch: defaultWatch, + }), }) ); }); @@ -123,7 +102,7 @@ describe('', () => { describe('Threshold watch', () => { const watch = getWatch({ - id: getRandomString(), + id: WATCH_ID, type: 'threshold', name: 'my_threshold_watch', timeField: '@timestamp', @@ -138,9 +117,9 @@ describe('', () => { }); beforeEach(async () => { - httpRequestsMockHelpers.setLoadWatchResponse({ watch }); + httpRequestsMockHelpers.setLoadWatchResponse(WATCH_ID, { watch }); - testBed = await setup(); + testBed = await setup(httpSetup); testBed.component.update(); }); @@ -169,8 +148,6 @@ describe('', () => { actions.clickSubmitButton(); }); - const latestRequest = server.requests[server.requests.length - 1]; - const { id, type, @@ -185,25 +162,28 @@ describe('', () => { threshold, } = watch; - expect(latestRequest.requestBody).toEqual( - wrapBodyResponse({ - id, - name: EDITED_WATCH_NAME, - type, - isNew: false, - isActive: true, - actions: [], - timeField, - triggerIntervalSize, - triggerIntervalUnit, - aggType, - termSize, - termOrder: 'desc', - thresholdComparator, - timeWindowSize, - timeWindowUnit, - hasTermsAgg: false, - threshold: threshold && threshold[0], + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${watch.id}`, + expect.objectContaining({ + body: JSON.stringify({ + id, + name: EDITED_WATCH_NAME, + type, + isNew: false, + isActive: true, + actions: [], + timeField, + triggerIntervalSize, + triggerIntervalUnit, + aggType, + termSize, + termOrder: 'desc', + thresholdComparator, + timeWindowSize, + timeWindowUnit, + hasTermsAgg: false, + threshold: threshold && threshold[0], + }), }) ); }); diff --git a/x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts index 1a396a007dd0c..ac1e7291b187a 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_list.test.ts @@ -7,16 +7,14 @@ import { act } from 'react-dom/test-utils'; import * as fixtures from '../../__fixtures__'; -import { ROUTES } from '../../common/constants'; import { setupEnvironment, pageHelpers, getRandomString, findTestSubject } from './helpers'; import { WatchListTestBed } from './helpers/watch_list.helpers'; - -const { API_ROOT } = ROUTES; +import { API_BASE_PATH } from '../../common/constants'; const { setup } = pageHelpers.watchList; describe('', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchListTestBed; beforeAll(() => { @@ -25,7 +23,6 @@ describe('', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('on component mount', () => { @@ -35,7 +32,7 @@ describe('', () => { httpRequestsMockHelpers.setLoadWatchesResponse({ watches: [] }); await act(async () => { - testBed = await setup(); + testBed = await setup(httpSetup); }); testBed.component.update(); }); @@ -73,7 +70,7 @@ describe('', () => { httpRequestsMockHelpers.setLoadWatchesResponse({ watches }); await act(async () => { - testBed = await setup(); + testBed = await setup(httpSetup); }); testBed.component.update(); @@ -241,10 +238,10 @@ describe('', () => { confirmButton!.click(); }); - const latestRequest = server.requests[server.requests.length - 1]; - - expect(latestRequest.method).toBe('POST'); - expect(latestRequest.url).toBe(`${API_ROOT}/watches/delete`); + expect(httpSetup.post).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watches/delete`, + expect.anything() + ); }); }); }); diff --git a/x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts b/x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts index 1b1b813617da6..901ebf156911f 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/watch_status.test.ts @@ -8,12 +8,11 @@ import { act } from 'react-dom/test-utils'; import moment from 'moment'; import { getWatchHistory } from '../../__fixtures__'; -import { ROUTES, WATCH_STATES, ACTION_STATES } from '../../common/constants'; +import { WATCH_STATES, ACTION_STATES } from '../../common/constants'; import { setupEnvironment, pageHelpers } from './helpers'; import { WatchStatusTestBed } from './helpers/watch_status.helpers'; -import { WATCH } from './helpers/jest_constants'; - -const { API_ROOT } = ROUTES; +import { WATCH, WATCH_ID } from './helpers/jest_constants'; +import { API_BASE_PATH } from '../../common/constants'; const { setup } = pageHelpers.watchStatus; @@ -40,7 +39,7 @@ const watch = { }; describe('', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchStatusTestBed; beforeAll(() => { @@ -49,15 +48,14 @@ describe('', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('on component mount', () => { beforeEach(async () => { - httpRequestsMockHelpers.setLoadWatchResponse({ watch }); - httpRequestsMockHelpers.setLoadWatchHistoryResponse(watchHistoryItems); + httpRequestsMockHelpers.setLoadWatchResponse(WATCH_ID, { watch }); + httpRequestsMockHelpers.setLoadWatchHistoryResponse(WATCH_ID, watchHistoryItems); - testBed = await setup(); + testBed = await setup(httpSetup); testBed.component.update(); }); @@ -127,14 +125,14 @@ describe('', () => { const formattedStartTime = moment(watchHistoryItem.startTime).format(); - httpRequestsMockHelpers.setLoadWatchHistoryItemResponse({ watchHistoryItem }); + httpRequestsMockHelpers.setLoadWatchHistoryItemResponse(WATCH_ID, { watchHistoryItem }); await actions.clickWatchExecutionAt(0, formattedStartTime); - const latestRequest = server.requests[server.requests.length - 1]; - - expect(latestRequest.method).toBe('GET'); - expect(latestRequest.url).toBe(`${API_ROOT}/history/${watchHistoryItem.id}`); + expect(httpSetup.get).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/history/${watchHistoryItem.id}`, + expect.anything() + ); expect(exists('watchHistoryDetailFlyout')).toBe(true); }); @@ -179,10 +177,10 @@ describe('', () => { }); component.update(); - const latestRequest = server.requests[server.requests.length - 1]; - - expect(latestRequest.method).toBe('POST'); - expect(latestRequest.url).toBe(`${API_ROOT}/watches/delete`); + expect(httpSetup.post).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watches/delete`, + expect.anything() + ); }); }); @@ -190,7 +188,7 @@ describe('', () => { test('should send the correct HTTP request to deactivate and activate a watch', async () => { const { actions } = testBed; - httpRequestsMockHelpers.setDeactivateWatchResponse({ + httpRequestsMockHelpers.setDeactivateWatchResponse(WATCH_ID, { watchStatus: { state: WATCH_STATES.DISABLED, isActive: false, @@ -199,12 +197,12 @@ describe('', () => { await actions.clickToggleActivationButton(); - const deactivateRequest = server.requests[server.requests.length - 1]; - - expect(deactivateRequest.method).toBe('PUT'); - expect(deactivateRequest.url).toBe(`${API_ROOT}/watch/${watch.id}/deactivate`); + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${watch.id}/deactivate`, + expect.anything() + ); - httpRequestsMockHelpers.setActivateWatchResponse({ + httpRequestsMockHelpers.setActivateWatchResponse(WATCH_ID, { watchStatus: { state: WATCH_STATES.FIRING, isActive: true, @@ -213,10 +211,10 @@ describe('', () => { await actions.clickToggleActivationButton(); - const activateRequest = server.requests[server.requests.length - 1]; - - expect(activateRequest.method).toBe('PUT'); - expect(activateRequest.url).toBe(`${API_ROOT}/watch/${watch.id}/activate`); + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/${watch.id}/activate`, + expect.anything() + ); }); }); @@ -242,7 +240,7 @@ describe('', () => { test('should allow an action to be acknowledged', async () => { const { actions, table } = testBed; - httpRequestsMockHelpers.setAcknowledgeWatchResponse({ + httpRequestsMockHelpers.setAcknowledgeWatchResponse(WATCH_ID, ACTION_ID, { watchStatus: { state: WATCH_STATES.FIRING, isActive: true, @@ -259,11 +257,12 @@ describe('', () => { await actions.clickAcknowledgeButton(0); - const latestRequest = server.requests[server.requests.length - 1]; - - expect(latestRequest.method).toBe('PUT'); - expect(latestRequest.url).toBe( - `${API_ROOT}/watch/${watch.id}/action/${ACTION_ID}/acknowledge` + // In previous tests we make calls to activate and deactivate using the put method, + // so we need to expect that the acknowledge api call will be the third. + const indexOfAcknowledgeApiCall = 3; + expect(httpSetup.put).toHaveBeenNthCalledWith( + indexOfAcknowledgeApiCall, + `${API_BASE_PATH}/watch/${watch.id}/action/${ACTION_ID}/acknowledge` ); const { tableCellsValues } = table.getMetaData('watchActionStatusTable'); diff --git a/x-pack/plugins/watcher/common/constants/index.ts b/x-pack/plugins/watcher/common/constants/index.ts index 4d497ed1ea67f..153d4e087b064 100644 --- a/x-pack/plugins/watcher/common/constants/index.ts +++ b/x-pack/plugins/watcher/common/constants/index.ts @@ -16,7 +16,7 @@ export { LISTS } from './lists'; export { PAGINATION } from './pagination'; export { PLUGIN } from './plugin'; export { REFRESH_INTERVALS } from './refresh_intervals'; -export { ROUTES } from './routes'; +export { ROUTES, API_BASE_PATH } from './routes'; export { SORT_ORDERS } from './sort_orders'; export { TIME_UNITS } from './time_units'; export { WATCH_STATE_COMMENTS } from './watch_state_comments'; diff --git a/x-pack/plugins/watcher/common/constants/routes.ts b/x-pack/plugins/watcher/common/constants/routes.ts index c45c699c8e1bb..c7df203bb75da 100644 --- a/x-pack/plugins/watcher/common/constants/routes.ts +++ b/x-pack/plugins/watcher/common/constants/routes.ts @@ -5,6 +5,8 @@ * 2.0. */ +export const API_BASE_PATH = '/api/watcher'; + export const ROUTES: { [key: string]: string } = { - API_ROOT: '/api/watcher', + API_ROOT: API_BASE_PATH, };