From af6f6c61ec41722bc7d6cb88113a228df2f6c3be Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Tue, 29 Mar 2022 16:22:11 +0200 Subject: [PATCH 1/6] wip start refactoring tests --- .../helpers/app_context.mock.tsx | 11 - .../helpers/http_requests.ts | 233 +++++++++--------- ...p_environment.ts => setup_environment.tsx} | 35 ++- .../helpers/watch_create_json.helpers.ts | 9 +- .../helpers/watch_create_threshold.helpers.ts | 9 +- .../helpers/watch_edit.helpers.ts | 9 +- .../helpers/watch_list.helpers.ts | 8 +- .../helpers/watch_status.helpers.ts | 9 +- .../watch_create_json.test.ts | 91 +++---- .../watch_create_threshold.test.tsx | 139 ++++++----- .../plugins/watcher/common/constants/index.ts | 2 +- .../watcher/common/constants/routes.ts | 4 +- 12 files changed, 282 insertions(+), 277 deletions(-) rename x-pack/plugins/watcher/__jest__/client_integration/helpers/{setup_environment.ts => setup_environment.tsx} (54%) 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/http_requests.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/http_requests.ts index e98cd66a25684..1361aa56fea83 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,127 @@ * 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 defaultResponse = { watches: [] }; + const setLoadWatchesResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/watches`, response, error); + + // const defaultResponse = { watch: {} }; + const setLoadWatchResponse = (watchId: string, response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/watch/${watchId}`, response, error); + + // const defaultResponse = { watchHistoryItems: [] }; + const setLoadWatchHistoryResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('GET', `${API_ROOT}/watch/${watchId}/history`, response, error); + + // const defaultResponse = { watchHistoryItem: {} }; + 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 defaultResponse = { watchHistoryItem: {} }; + const setLoadExecutionResultResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('PUT', `${API_ROOT}/watch/execute`, response, error); + + // const defaultResponse = { indices: [] }; + const setLoadMatchingIndicesResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('PUT', `${API_ROOT}/indices`, response, error); + + // const defaultResponse = { fields: [] }; + const setLoadEsFieldsResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('POST', `${API_ROOT}/fields`, response, error); + + // const defaultResponse = { action_types: {} }; + const setLoadSettingsResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('GET', `${API_ROOT}/settings`, response, error); + + // const defaultResponse = { visualizeData: {} }; + const setLoadWatchVisualizeResponse = (response?: HttpResponse, error?: ResponseError) => + mockResponse('POST', `${API_ROOT}/watch/visualize`, response, error); + + // const defaultResponse = { watchStatus: {} }; + const setDeactivateWatchResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/deactivate`, response, error); + + // const defaultResponse = { watchStatus: {} }; + const setActivateWatchResponse = ( + watchId: string, + response?: HttpResponse, + error?: ResponseError + ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/activate`, response, error); + + // const defaultResponse = { watchStatus: {} }; + 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 +146,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/setup_environment.ts b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx similarity index 54% rename from x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts rename to x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx index 5ba0387d21ba7..f42b452818cc5 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.ts +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/setup_environment.tsx @@ -5,38 +5,33 @@ * 2.0. */ -import axios from 'axios'; -import axiosXhrAdapter from 'axios/lib/adapters/xhr'; +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 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(); +export const WithAppDependencies = + (Component: any, httpSetup: HttpSetup) => (props: Record) => { + setHttpClient(httpSetup); - // @ts-ignore - setHttpClient(mockHttpClient); + return ( + + + + ); + }; +export const setupEnvironment = () => { setSavedObjectsClient(mockSavedObjectsClient() as any); - return { - server, - httpRequestsMockHelpers, - }; + 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 16e4930510efa..4e76a1687114a 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-helpers'; +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 cbfdac67597e1..5a8d7b23e0b58 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-helpers'; +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 9f01750d43593..9eb35f3f1bb32 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-helpers'; +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 914eaca62465d..f7aca95039863 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 @@ -13,9 +13,10 @@ import { TestBed, AsyncTestBedConfig, } from '@kbn/test-jest-helpers'; +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: { @@ -24,8 +25,6 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchList), testBedConfig); - export interface WatchListTestBed extends TestBed { actions: { selectWatchAt: (index: number) => void; @@ -35,7 +34,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 63892961d8b57..03ee2e12410fc 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 @@ -13,10 +13,12 @@ import { TestBed, AsyncTestBedConfig, } from '@kbn/test-jest-helpers'; +import { HttpSetup } from 'src/core/public'; + 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: { @@ -26,8 +28,6 @@ const testBedConfig: AsyncTestBedConfig = { doMountAsync: true, }; -const initTestBed = registerTestBed(withAppContext(WatchStatus), testBedConfig); - export interface WatchStatusTestBed extends TestBed { actions: { selectTab: (tab: 'execution history' | 'action statuses') => void; @@ -38,7 +38,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 52c3a69938d74..9110a63e7ec88 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 @@ -11,7 +11,7 @@ import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import axios from 'axios'; import { getExecuteDetails } from '../../__fixtures__'; -import { WATCH_TYPES } from '../../common/constants'; +import { WATCH_TYPES, API_BASE_PATH } from '../../common/constants'; import { setupEnvironment, pageHelpers, wrapBodyResponse, unwrapBodyResponse } from './helpers'; import { WatchCreateThresholdTestBed } from './helpers/watch_create_threshold.helpers'; @@ -23,6 +23,12 @@ const MATCH_INDICES = ['index1']; const ES_FIELDS = [{ name: '@timestamp', type: 'date' }]; +jest.mock('uuid/v4', () => { + return function () { + return '12345'; + }; +}); + const SETTINGS = { action_types: { email: { enabled: true }, @@ -77,7 +83,7 @@ jest.mock('@elastic/eui', () => { const { setup } = pageHelpers.watchCreateThreshold; describe(' create route', () => { - const { server, httpRequestsMockHelpers } = setupEnvironment(); + const { httpSetup, httpRequestsMockHelpers } = setupEnvironment(); let testBed: WatchCreateThresholdTestBed; beforeAll(() => { @@ -86,14 +92,12 @@ describe(' create route', () => { afterAll(() => { jest.useRealTimers(); - server.restore(); }); describe('on component mount', () => { beforeEach(async () => { - testBed = await setup(); - const { component } = testBed; - component.update(); + testBed = await setup(httpSetup); + testBed.component.update(); }); test('should set the correct page title', () => { @@ -108,6 +112,12 @@ describe(' create route', () => { httpRequestsMockHelpers.setLoadEsFieldsResponse({ fields: ES_FIELDS }); httpRequestsMockHelpers.setLoadSettingsResponse(SETTINGS); httpRequestsMockHelpers.setLoadWatchVisualizeResponse(WATCH_VISUALIZE_DATA); + + await act(async () => { + testBed = await setup(httpSetup); + }); + + testBed.component.update(); }); describe('form validation', () => { @@ -211,7 +221,7 @@ describe(' create route', () => { }); }); - describe('actions', () => { + describe.skip('actions', () => { beforeEach(async () => { const { form, find, component } = testBed; @@ -751,7 +761,7 @@ describe(' create route', () => { }); }); - describe('watch visualize data payload', () => { + describe.skip('watch visualize data payload', () => { test('should send the correct payload', async () => { const { form, find, component } = testBed; @@ -763,37 +773,40 @@ describe(' create route', () => { }); component.update(); - const latestReqToGetVisualizeData = server.requests.find( - (req) => req.method === 'POST' && req.url === '/api/watcher/watch/visualize' + // 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); + + expect(httpSetup.put).toHaveBeenLastCalledWith( + `${API_BASE_PATH}/watch/12345`, + expect.objectContaining({ + body: JSON.stringify({ + id: '12345', + name: 'my_test_watch', + type: 'threshold', + isNew: true, + isActive: true, + actions: [], + index: ['index1'], + timeField: '@timestamp', + triggerIntervalSize: 1, + triggerIntervalUnit: 'm', + aggType: 'count', + termSize: 5, + termOrder: 'desc', + thresholdComparator: '>', + timeWindowSize: 5, + timeWindowUnit: 'm', + hasTermsAgg: false, + threshold: 1000, + }), + }) ); - if (!latestReqToGetVisualizeData) { - throw new Error(`No request found to fetch visualize data.`); - } - - const requestBody = unwrapBodyResponse(latestReqToGetVisualizeData.requestBody); - - expect(requestBody.watch).toEqual({ - id: requestBody.watch.id, // id is dynamic - name: 'my_test_watch', - type: 'threshold', - isNew: true, - isActive: true, - actions: [], - index: ['index1'], - timeField: '@timestamp', - triggerIntervalSize: 1, - triggerIntervalUnit: 'm', - aggType: 'count', - termSize: 5, - termOrder: 'desc', - thresholdComparator: '>', - timeWindowSize: 5, - timeWindowUnit: 'm', - hasTermsAgg: false, - threshold: 1000, - }); - - expect(requestBody.options.interval).toBeDefined(); }); }); @@ -813,31 +826,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/12345`, + expect.objectContaining({ + body: JSON.stringify({ + id: '12345', + 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/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, }; From a182c816e1a6ad1dafb162b8133ed6fb048b529e Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Tue, 29 Mar 2022 16:27:19 +0200 Subject: [PATCH 2/6] commit using @elastic.co From 3df88730c6bd3601b370a7bde59cd72b32faa0f1 Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Wed, 30 Mar 2022 10:35:19 +0200 Subject: [PATCH 3/6] Finish refactoring tests --- .../helpers/watch_status.helpers.ts | 2 + .../watch_create_threshold.test.tsx | 282 ++++++++---------- .../client_integration/watch_edit.test.ts | 112 ++++--- .../client_integration/watch_list.test.ts | 19 +- .../client_integration/watch_status.test.ts | 64 ++-- 5 files changed, 220 insertions(+), 259 deletions(-) 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 03ee2e12410fc..ab2204f4a6dfe 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 @@ -15,6 +15,7 @@ import { } from '@kbn/test-jest-helpers'; import { HttpSetup } from 'src/core/public'; +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'; @@ -22,6 +23,7 @@ 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`, }, 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 9110a63e7ec88..b753d08c76557 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,10 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; -import axiosXhrAdapter from 'axios/lib/adapters/xhr'; -import axios from 'axios'; import { getExecuteDetails } from '../../__fixtures__'; import { WATCH_TYPES, API_BASE_PATH } from '../../common/constants'; -import { setupEnvironment, pageHelpers, wrapBodyResponse, unwrapBodyResponse } from './helpers'; +import { setupEnvironment, pageHelpers } from './helpers'; import { WatchCreateThresholdTestBed } from './helpers/watch_create_threshold.helpers'; const WATCH_NAME = 'my_test_watch'; @@ -42,24 +40,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, - getHttpClient: () => mockHttpClient, - }; -}); - jest.mock('@elastic/eui', () => { const original = jest.requireActual('@elastic/eui'); @@ -96,7 +85,10 @@ describe(' create route', () => { describe('on component mount', () => { beforeEach(async () => { - testBed = await setup(httpSetup); + await act(async () => { + testBed = await setup(httpSetup); + }); + testBed.component.update(); }); @@ -112,12 +104,6 @@ describe(' create route', () => { httpRequestsMockHelpers.setLoadEsFieldsResponse({ fields: ES_FIELDS }); httpRequestsMockHelpers.setLoadSettingsResponse(SETTINGS); httpRequestsMockHelpers.setLoadWatchVisualizeResponse(WATCH_VISUALIZE_DATA); - - await act(async () => { - testBed = await setup(httpSetup); - }); - - testBed.component.update(); }); describe('form validation', () => { @@ -169,6 +155,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); @@ -221,7 +208,7 @@ describe(' create route', () => { }); }); - describe.skip('actions', () => { + describe('actions', () => { beforeEach(async () => { const { form, find, component } = testBed; @@ -257,11 +244,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -290,16 +274,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, }) ); }); @@ -319,11 +306,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -351,16 +335,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, }) ); }); @@ -381,11 +368,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -416,16 +400,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, }) ); }); @@ -453,11 +440,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -492,16 +476,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, }) ); }); @@ -545,11 +532,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -586,16 +570,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, }) ); }); @@ -633,11 +620,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -676,16 +660,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, }) ); }); @@ -713,11 +700,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: '12345', name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -746,22 +730,25 @@ 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, }) ); }); }); - describe.skip('watch visualize data payload', () => { + describe('watch visualize data payload', () => { test('should send the correct payload', async () => { const { form, find, component } = testBed; @@ -773,40 +760,31 @@ 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: any[] = httpSetup.post.mock.calls.pop() || []; + // Options contains two dinamically computed timestamps, so its simpler to just ignore those fields. + const { options, ...body } = JSON.parse(lastReq[1].body).watch; - expect(httpSetup.put).toHaveBeenLastCalledWith( - `${API_BASE_PATH}/watch/12345`, - expect.objectContaining({ - body: JSON.stringify({ - id: '12345', - name: 'my_test_watch', - type: 'threshold', - isNew: true, - isActive: true, - actions: [], - index: ['index1'], - timeField: '@timestamp', - triggerIntervalSize: 1, - triggerIntervalUnit: 'm', - aggType: 'count', - termSize: 5, - termOrder: 'desc', - thresholdComparator: '>', - timeWindowSize: 5, - timeWindowUnit: 'm', - hasTermsAgg: false, - threshold: 1000, - }), - }) - ); + expect(lastReq[0]).toBe(`${API_BASE_PATH}/watch/visualize`); + expect(body).toEqual({ + id: '12345', + name: 'my_test_watch', + type: 'threshold', + isNew: true, + isActive: true, + actions: [], + index: ['index1'], + timeField: '@timestamp', + 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 37f9838f176af..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,31 +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-helpers'; 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, - 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(() => { @@ -39,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(); }); @@ -82,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, + }), }) ); }); @@ -115,7 +102,7 @@ describe('', () => { describe('Threshold watch', () => { const watch = getWatch({ - id: getRandomString(), + id: WATCH_ID, type: 'threshold', name: 'my_threshold_watch', timeField: '@timestamp', @@ -130,9 +117,9 @@ describe('', () => { }); beforeEach(async () => { - httpRequestsMockHelpers.setLoadWatchResponse({ watch }); + httpRequestsMockHelpers.setLoadWatchResponse(WATCH_ID, { watch }); - testBed = await setup(); + testBed = await setup(httpSetup); testBed.component.update(); }); @@ -161,8 +148,6 @@ describe('', () => { actions.clickSubmitButton(); }); - const latestRequest = server.requests[server.requests.length - 1]; - const { id, type, @@ -177,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..f5b635b538f5e 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,9 @@ 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` + expect(httpSetup.put).toHaveBeenNthCalledWith( + 3, + `${API_BASE_PATH}/watch/${watch.id}/action/${ACTION_ID}/acknowledge` ); const { tableCellsValues } = table.getMetaData('watchActionStatusTable'); From 24165d32743eb19faa634553717fd1fb84e87007 Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Wed, 30 Mar 2022 11:12:44 +0200 Subject: [PATCH 4/6] Remove unused code --- .../client_integration/helpers/body_response.ts | 10 ---------- .../client_integration/helpers/http_requests.ts | 12 ------------ .../__jest__/client_integration/helpers/index.ts | 1 - 3 files changed, 23 deletions(-) delete mode 100644 x-pack/plugins/watcher/__jest__/client_integration/helpers/body_response.ts 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 1361aa56fea83..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 @@ -51,22 +51,18 @@ const registerHttpRequestMockHelpers = ( .set(path, error ? defuse(Promise.reject(error)) : Promise.resolve(response)); }; - // const defaultResponse = { watches: [] }; const setLoadWatchesResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('GET', `${API_ROOT}/watches`, response, error); - // const defaultResponse = { watch: {} }; const setLoadWatchResponse = (watchId: string, response?: HttpResponse, error?: ResponseError) => mockResponse('GET', `${API_ROOT}/watch/${watchId}`, response, error); - // const defaultResponse = { watchHistoryItems: [] }; const setLoadWatchHistoryResponse = ( watchId: string, response?: HttpResponse, error?: ResponseError ) => mockResponse('GET', `${API_ROOT}/watch/${watchId}/history`, response, error); - // const defaultResponse = { watchHistoryItem: {} }; const setLoadWatchHistoryItemResponse = ( watchId: string, response?: HttpResponse, @@ -79,41 +75,33 @@ const registerHttpRequestMockHelpers = ( const setSaveWatchResponse = (watchId: string, response?: HttpResponse, error?: ResponseError) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}`, response, error); - // const defaultResponse = { watchHistoryItem: {} }; const setLoadExecutionResultResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('PUT', `${API_ROOT}/watch/execute`, response, error); - // const defaultResponse = { indices: [] }; const setLoadMatchingIndicesResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('PUT', `${API_ROOT}/indices`, response, error); - // const defaultResponse = { fields: [] }; const setLoadEsFieldsResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('POST', `${API_ROOT}/fields`, response, error); - // const defaultResponse = { action_types: {} }; const setLoadSettingsResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('GET', `${API_ROOT}/settings`, response, error); - // const defaultResponse = { visualizeData: {} }; const setLoadWatchVisualizeResponse = (response?: HttpResponse, error?: ResponseError) => mockResponse('POST', `${API_ROOT}/watch/visualize`, response, error); - // const defaultResponse = { watchStatus: {} }; const setDeactivateWatchResponse = ( watchId: string, response?: HttpResponse, error?: ResponseError ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/deactivate`, response, error); - // const defaultResponse = { watchStatus: {} }; const setActivateWatchResponse = ( watchId: string, response?: HttpResponse, error?: ResponseError ) => mockResponse('PUT', `${API_ROOT}/watch/${watchId}/activate`, response, error); - // const defaultResponse = { watchStatus: {} }; const setAcknowledgeWatchResponse = ( watchId: string, actionId: string, 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 07ced2096e696..4fbcb847022e9 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-helpers'; export { getRandomString, findTestSubject } from '@kbn/test-jest-helpers'; -export { wrapBodyResponse, unwrapBodyResponse } from './body_response'; export { setupEnvironment } from './setup_environment'; export const pageHelpers = { From 0b708a6667ca62c58c8ac41c3be0a3c25196547f Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Wed, 30 Mar 2022 11:15:40 +0200 Subject: [PATCH 5/6] Add docs --- .../client_integration/watch_create_threshold.test.tsx | 3 +++ 1 file changed, 3 insertions(+) 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 b753d08c76557..e0ea76b20bfdb 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 @@ -21,6 +21,9 @@ 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', () => { return function () { return '12345'; From 7c9f134736c3bec95480ab96ead2d4bf05055f11 Mon Sep 17 00:00:00 2001 From: Ignacio Rivas Date: Wed, 30 Mar 2022 16:00:26 +0200 Subject: [PATCH 6/6] Address CR changes --- .../watch_create_threshold.test.tsx | 36 +++++++++++-------- .../client_integration/watch_status.test.ts | 5 ++- 2 files changed, 25 insertions(+), 16 deletions(-) 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 e0ea76b20bfdb..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 @@ -8,6 +8,8 @@ import React from 'react'; import { act } from 'react-dom/test-utils'; +import { HttpFetchOptionsWithPath } from 'kibana/public'; +import { WATCH_ID } from './helpers/jest_constants'; import { getExecuteDetails } from '../../__fixtures__'; import { WATCH_TYPES, API_BASE_PATH } from '../../common/constants'; import { setupEnvironment, pageHelpers } from './helpers'; @@ -25,8 +27,11 @@ const ES_FIELDS = [{ name: '@timestamp', type: 'date' }]; // 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 '12345'; + return watchId; }; }); @@ -248,7 +253,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -310,7 +315,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -372,7 +377,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -444,7 +449,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -536,7 +541,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -624,7 +629,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -704,7 +709,7 @@ describe(' create route', () => { }); const thresholdWatch = { - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, @@ -763,13 +768,14 @@ describe(' create route', () => { }); component.update(); - const lastReq: any[] = httpSetup.post.mock.calls.pop() || []; - // Options contains two dinamically computed timestamps, so its simpler to just ignore those fields. - const { options, ...body } = JSON.parse(lastReq[1].body).watch; + 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(lastReq[0]).toBe(`${API_BASE_PATH}/watch/visualize`); + expect(requestUrl).toBe(`${API_BASE_PATH}/watch/visualize`); expect(body).toEqual({ - id: '12345', + id: WATCH_ID, name: 'my_test_watch', type: 'threshold', isNew: true, @@ -808,10 +814,10 @@ describe(' create route', () => { }); expect(httpSetup.put).toHaveBeenLastCalledWith( - `${API_BASE_PATH}/watch/12345`, + `${API_BASE_PATH}/watch/${WATCH_ID}`, expect.objectContaining({ body: JSON.stringify({ - id: '12345', + id: WATCH_ID, name: WATCH_NAME, type: WATCH_TYPES.THRESHOLD, isNew: true, 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 f5b635b538f5e..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 @@ -257,8 +257,11 @@ describe('', () => { await actions.clickAcknowledgeButton(0); + // 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( - 3, + indexOfAcknowledgeApiCall, `${API_BASE_PATH}/watch/${watch.id}/action/${ACTION_ID}/acknowledge` );