Skip to content

Commit

Permalink
test bed fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mattkime committed Apr 8, 2022
1 parent ce900bc commit 4473136
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,12 @@ describe('Field editor Preview panel', () => {
];

beforeEach(async () => {
// server.respondImmediately = true;
// server.autoRespond = true;

httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['mockedScriptValue'] });
setIndexPatternFields(indexPatternFields);
setSearchResponse(mockDocuments);
setSearchResponseLatency(0);

// testBed = await setup(undefined, { server });
testBed = await setup();
});

Expand Down Expand Up @@ -290,12 +288,10 @@ describe('Field editor Preview panel', () => {
await fields.updateName('myRuntimeField');
await fields.updateScript('echo("hello")');
await waitForUpdates(); // Run validations
// todo might not need anymore
// const request = getLatestPreviewHttpRequest(server);

// Make sure the payload sent is correct
console.log('checking calls');
expect(server.post.mock.calls[0]).toEqual({
const payload = JSON.parse(server.post.mock.calls[0][1]?.body);
expect(payload).toEqual({
context: 'keyword_field',
document: {
description: 'First doc - description',
Expand Down Expand Up @@ -374,10 +370,8 @@ describe('Field editor Preview panel', () => {
test('should display an updating indicator while fetching the docs and the preview', async () => {
// We want to test if the loading indicator is in the DOM, for that we don't want the server to
// respond immediately. We'll manualy send the response.
// server.respondImmediately = false;
// server.autoRespond = false;

httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] });
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] }, undefined, true);

const {
exists,
Expand All @@ -401,11 +395,9 @@ describe('Field editor Preview panel', () => {
});

test('should not display the updating indicator when neither the type nor the script has changed', async () => {
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] });
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] }, undefined, true);
// We want to test if the loading indicator is in the DOM, for that we need to manually
// send the response from the server
// server.respondImmediately = false;
// server.autoRespond = false;

const {
exists,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,97 +7,36 @@
*/

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

type HttpMethod = 'GET' | 'PUT' | 'DELETE' | 'POST';

type HttpResponse = Record<string, any> | any[];

const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>,
shouldDelayResponse: () => boolean
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) => {
const responsePromise = mockResponses.get(method)?.get(path) ?? Promise.resolve({});
if (shouldDelayResponse()) {
return new Promise((resolve) => {
setTimeout(() => resolve(responsePromise), 1000);
});
}
return responsePromise;
};
*/
const setFieldPreviewResponse = (response?: HttpResponse, error?: any, delayResponse = false) => {
const body = error ? JSON.stringify(error.body) : response;

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

console.log('settingFieldPreviewResponse');
httpSetup.post.mockImplementation(() => {
console.log('calling mocked post');
return Promise.resolve([status, { 'Content-Type': 'application/json' }, body]);
if (delayResponse) {
return new Promise((resolve) => {
setTimeout(() => resolve({ data: body }), 1000);
});
} else {
return Promise.resolve({ data: body });
}
});
};
return {
setFieldPreviewResponse,
};
};

// Register helpers to mock HTTP Requests
/*
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>,
shouldDelayResponse: () => boolean
) => {
const setFieldPreviewResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.body.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);
server.respondWith('POST', `${API_BASE_PATH}/field_preview`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
return {
setFieldPreviewResponse,
};
};
*/

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, {}, 'DefaultSinonMockServerResponse']);
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(server);
*/

let isResponseDelayed = false;
const getDelayResponse = () => isResponseDelayed;
const setDelayResponse = (shouldDelayResponse: boolean) => {
isResponseDelayed = shouldDelayResponse;
};

const httpSetup = httpServiceMock.createSetupContract();
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup, getDelayResponse);
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup);

return {
httpSetup,
setDelayResponse,
httpRequestsMockHelpers,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ import './jest.mocks';
import React, { FunctionComponent } from 'react';
import { merge } from 'lodash';

import {
notificationServiceMock,
uiSettingsServiceMock,
httpServiceMock,
} from '../../../../../core/public/mocks';
import { notificationServiceMock, uiSettingsServiceMock } from '../../../../../core/public/mocks';
import { dataPluginMock } from '../../../../data/public/mocks';
import { FieldEditorProvider, Context } from '../../../public/components/field_editor_context';
import { FieldPreviewProvider } from '../../../public/components/preview';
Expand All @@ -25,7 +21,6 @@ import { init as initHttpRequests } from './http_requests';
import { fieldFormatsMock as fieldFormats } from '../../../../field_formats/common/mocks';
import { FieldFormat } from '../../../../field_formats/common';

const mockHttpClient = httpServiceMock.createStartContract();
const dataStart = dataPluginMock.createStartContract();
const { search } = dataStart;

Expand Down Expand Up @@ -63,8 +58,8 @@ search.search = spySearchQuery;
let apiService: ApiService;

export const setupEnvironment = () => {
apiService = initApi(mockHttpClient);
const { httpSetup, httpRequestsMockHelpers } = initHttpRequests();
apiService = initApi(httpSetup);

return {
server: httpSetup,
Expand Down

0 comments on commit 4473136

Please sign in to comment.