Skip to content

Commit

Permalink
[Watcher] Remove axios dependency in tests (#128765)
Browse files Browse the repository at this point in the history
* wip start refactoring tests

* commit using @elastic.co

* Finish refactoring tests

* Remove unused code

* Add docs

* Address CR changes
  • Loading branch information
sabarasaba authored Mar 31, 2022
1 parent c938b72 commit 1caaaba
Show file tree
Hide file tree
Showing 17 changed files with 440 additions and 485 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-helpers';
export { getRandomString, findTestSubject } from '@kbn/test-jest-helpers';
export { wrapBodyResponse, unwrapBodyResponse } from './body_response';
export { setupEnvironment } from './setup_environment';

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

// @ts-ignore
setHttpClient(mockHttpClient);
return (
<AppContextProvider value={mockContextValue}>
<Component {...props} />
</AppContextProvider>
);
};

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

return {
server,
httpRequestsMockHelpers,
};
return initHttpRequests();
};
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -20,8 +22,6 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(withAppContext(WatchEdit), testBedConfig);

export interface WatchCreateJsonTestBed extends TestBed<WatchCreateJsonTestSubjects> {
actions: {
selectTab: (tab: 'edit' | 'simulate') => void;
Expand All @@ -30,7 +30,8 @@ export interface WatchCreateJsonTestBed extends TestBed<WatchCreateJsonTestSubje
};
}

export const setup = async (): Promise<WatchCreateJsonTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<WatchCreateJsonTestBed> => {
const initTestBed = registerTestBed(WithAppDependencies(WatchEdit, httpSetup), testBedConfig);
const testBed = await initTestBed();

/**
Expand Down
Loading

0 comments on commit 1caaaba

Please sign in to comment.