Skip to content

Commit

Permalink
[7.17] [Watcher] Remove axios dependency in tests (#128765) (#129004)
Browse files Browse the repository at this point in the history
* [Watcher] Remove `axios` dependency in tests (#128765)

* wip start refactoring tests

* commit using @elastic.co

* Finish refactoring tests

* Remove unused code

* Add docs

* Address CR changes

(cherry picked from commit 1caaaba)

# Conflicts:
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/index.ts
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_json.helpers.ts
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_create_threshold.helpers.ts
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_edit.helpers.ts
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_list.helpers.ts
#	x-pack/plugins/watcher/__jest__/client_integration/helpers/watch_status.helpers.ts
#	x-pack/plugins/watcher/__jest__/client_integration/watch_create_threshold.test.tsx
#	x-pack/plugins/watcher/__jest__/client_integration/watch_edit.test.ts

* Fix test and linter

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
sabarasaba and kibanamachine authored Apr 4, 2022
1 parent 1a56bb2 commit 1010bd6
Show file tree
Hide file tree
Showing 18 changed files with 465 additions and 523 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
* 2.0.
*/

import React from 'react';
import { of } from 'rxjs';
import { ComponentType } from 'enzyme';
import { LocationDescriptorObject } from 'history';

import {
Expand All @@ -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';

Expand Down Expand Up @@ -52,11 +49,3 @@ export const mockContextValue: AppDeps = {
history,
getUrlForApp: jest.fn(),
};

export const withAppContext = (Component: ComponentType<any>) => (props: any) => {
return (
<AppContextProvider value={mockContextValue}>
<Component {...props} />
</AppContextProvider>
);
};

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> | 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<typeof httpServiceMock.createStartContract>
) => {
const mockResponses = new Map<HttpMethod, Map<string, Promise<unknown>>>(
['GET', 'PUT', 'POST'].map(
(method) => [method, new Map()] as [HttpMethod, Map<string, Promise<unknown>>]
)
);

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<unknown>) => {
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,
Expand All @@ -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,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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<string, unknown>) => {
setHttpClient(httpSetup);

return (
<AppContextProvider value={mockContextValue}>
<Component {...props} />
</AppContextProvider>
);
};

export const setupEnvironment = () => {
setSavedObjectsClient(mockSavedObjectsClient() as any);

return initHttpRequests();
};
Loading

0 comments on commit 1010bd6

Please sign in to comment.