Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Ingest Pipelines] Remove axios dependency in tests #128467

Merged
merged 10 commits into from
Mar 30, 2022
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -5,63 +5,73 @@
* 2.0.
*/

import sinon, { SinonFakeServer } from 'sinon';

import { httpServiceMock } from '../../../../../../src/core/public/mocks';
import { API_BASE_PATH } from '../../../common/constants';

// Register helpers to mock HTTP Requests
const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
const setLoadPipelinesResponse = (response?: any[], error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? error.body : response;
type HttpMethod = 'GET' | 'PUT' | 'DELETE' | 'POST';
export interface ResponseError {
statusCode: number;
message: string | Error;
attributes?: Record<string, any>;
}

server.respondWith('GET', API_BASE_PATH, [
status,
{ 'Content-Type': 'application/json' },
JSON.stringify(body),
]);
// Register helpers to mock HTTP Requests
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>
) => {
const mockResponses = new Map<HttpMethod, Map<string, Promise<unknown>>>(
['GET', 'PUT', 'DELETE', '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.delete.mockImplementation((path) =>
mockMethodImplementation('DELETE', 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({ body: error })) : Promise.resolve(response));
};

const setLoadPipelineResponse = (response?: {}, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? error.body : response;
const setLoadPipelinesResponse = (response?: object[], error?: ResponseError) =>
mockResponse('GET', API_BASE_PATH, response, error);

server.respondWith('GET', `${API_BASE_PATH}/:name`, [
status,
{ 'Content-Type': 'application/json' },
JSON.stringify(body),
]);
};
const setLoadPipelineResponse = (
pipelineName: string,
response?: object,
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}/${pipelineName}`, response, error);

const setDeletePipelineResponse = (response?: object) => {
server.respondWith('DELETE', `${API_BASE_PATH}/:name`, [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
};
const setDeletePipelineResponse = (
pipelineName: string,
response?: object,
error?: ResponseError
) => mockResponse('DELETE', `${API_BASE_PATH}/${pipelineName}`, response, error);

const setCreatePipelineResponse = (response?: object, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);
const setCreatePipelineResponse = (response?: object, error?: ResponseError) =>
mockResponse('POST', API_BASE_PATH, response, error);

server.respondWith('POST', API_BASE_PATH, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};

const setParseCsvResponse = (response?: object, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);

server.respondWith('POST', `${API_BASE_PATH}/parse_csv`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
const setParseCsvResponse = (response?: object, error?: ResponseError) =>
mockResponse('POST', `${API_BASE_PATH}/parse_csv`, response, error);

return {
setLoadPipelinesResponse,
Expand All @@ -73,18 +83,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, {}, 'DefaultMockedResponse']);

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 @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig, TestBed } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PipelinesClone } from '../../../public/application/sections/pipelines_clone';
import { getFormActions, PipelineFormTestSubjects } from './pipeline_form.helpers';
import { WithAppDependencies } from './setup_environment';
Expand Down Expand Up @@ -36,9 +37,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(PipelinesClone), testBedConfig);

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

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig, TestBed } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PipelinesCreate } from '../../../public/application/sections/pipelines_create';
import { getFormActions, PipelineFormTestSubjects } from './pipeline_form.helpers';
import { WithAppDependencies } from './setup_environment';
Expand All @@ -23,9 +24,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(PipelinesCreate), testBedConfig);

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

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
*/

import { act } from 'react-dom/test-utils';

import { HttpSetup } from 'src/core/public';
import { registerTestBed, TestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';

import { PipelinesCreateFromCsv } from '../../../public/application/sections/pipelines_create_from_csv';
import { WithAppDependencies } from './setup_environment';
import { getCreateFromCsvPath, ROUTES } from '../../../public/application/services/navigation';
Expand All @@ -20,8 +21,6 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(PipelinesCreateFromCsv), testBedConfig);

export type PipelineCreateFromCsvTestBed = TestBed<PipelineCreateFromCsvTestSubjects> & {
actions: ReturnType<typeof createFromCsvActions>;
};
Expand Down Expand Up @@ -59,7 +58,11 @@ const createFromCsvActions = (testBed: TestBed) => {
};
};

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

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig, TestBed } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PipelinesEdit } from '../../../public/application/sections/pipelines_edit';
import { getFormActions, PipelineFormTestSubjects } from './pipeline_form.helpers';
import { WithAppDependencies } from './setup_environment';
Expand Down Expand Up @@ -36,9 +37,8 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(PipelinesEdit), testBedConfig);

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

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { act } from 'react-dom/test-utils';
import { HttpSetup } from 'src/core/public';

import {
registerTestBed,
Expand All @@ -25,8 +26,6 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(PipelinesList), testBedConfig);

export type PipelineListTestBed = TestBed<PipelineListTestSubjects> & {
actions: ReturnType<typeof createActions>;
};
Expand Down Expand Up @@ -89,7 +88,8 @@ const createActions = (testBed: TestBed) => {
};
};

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

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
*/

import React from 'react';
import axios from 'axios';
import axiosXhrAdapter from 'axios/lib/adapters/xhr';
import { LocationDescriptorObject } from 'history';
import { HttpSetup } from 'kibana/public';

Expand All @@ -34,8 +32,6 @@ import {

import { init as initHttpRequests } from './http_requests';

const mockHttpClient = axios.create({ adapter: axiosXhrAdapter });

const history = scopedHistoryMock.create();
history.createHref.mockImplementation((location: LocationDescriptorObject) => {
return `${location.pathname}?${location.search}`;
Expand Down Expand Up @@ -73,22 +69,19 @@ const appServices = {
};

export const setupEnvironment = () => {
uiMetricService.setup(usageCollectionPluginMock.createSetupContract());
apiService.setup(mockHttpClient as unknown as HttpSetup, uiMetricService);
documentationService.setup(docLinksServiceMock.createStartContract());
breadcrumbService.setup(() => {});

const { server, httpRequestsMockHelpers } = initHttpRequests();

return {
server,
httpRequestsMockHelpers,
};
return initHttpRequests();
};

export const WithAppDependencies = (Comp: any) => (props: any) =>
(
export const WithAppDependencies = (Comp: any, httpSetup: HttpSetup) => (props: any) => {
uiMetricService.setup(usageCollectionPluginMock.createSetupContract());
apiService.setup(httpSetup, uiMetricService);

return (
<KibanaContextProvider services={appServices}>
<Comp {...props} />
</KibanaContextProvider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import React from 'react';
import { act } from 'react-dom/test-utils';

import { setupEnvironment, pageHelpers } from './helpers';
import { API_BASE_PATH } from '../../common/constants';
import { PIPELINE_TO_CLONE, PipelinesCloneTestBed } from './helpers/pipelines_clone.helpers';

const { setup } = pageHelpers.pipelinesClone;
Expand All @@ -33,17 +34,13 @@ jest.mock('@elastic/eui', () => {
describe('<PipelinesClone />', () => {
let testBed: PipelinesCloneTestBed;

const { server, httpRequestsMockHelpers } = setupEnvironment();

afterAll(() => {
server.restore();
});

httpRequestsMockHelpers.setLoadPipelineResponse(PIPELINE_TO_CLONE);
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();

beforeEach(async () => {
httpRequestsMockHelpers.setLoadPipelineResponse(PIPELINE_TO_CLONE.name, PIPELINE_TO_CLONE);

await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});

testBed.component.update();
Expand All @@ -67,14 +64,15 @@ describe('<PipelinesClone />', () => {

await actions.clickSubmitButton();

const latestRequest = server.requests[server.requests.length - 1];

const expected = {
...PIPELINE_TO_CLONE,
name: `${PIPELINE_TO_CLONE.name}-copy`,
};

expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual(expected);
expect(httpSetup.post).toHaveBeenLastCalledWith(
API_BASE_PATH,
expect.objectContaining({
body: JSON.stringify({
...PIPELINE_TO_CLONE,
name: `${PIPELINE_TO_CLONE.name}-copy`,
}),
})
);
});
});
});
Loading