Skip to content

Commit

Permalink
partial progress
Browse files Browse the repository at this point in the history
  • Loading branch information
mattkime committed Apr 7, 2022
1 parent 9261a1a commit ce900bc
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ import { setup } from './field_editor_flyout_content.helpers';
import { mockDocuments, createPreviewError } from './helpers/mocks';

describe('<FieldEditorFlyoutContent />', () => {
const { server, httpRequestsMockHelpers } = setupEnvironment();
const { httpRequestsMockHelpers } = setupEnvironment();

beforeAll(() => {
jest.useFakeTimers();
});

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

beforeEach(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ describe('Field editor Preview panel', () => {

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

let testBed: FieldEditorFlyoutContentTestBed;
Expand All @@ -55,8 +54,8 @@ describe('Field editor Preview panel', () => {
];

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

httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['mockedScriptValue'] });
setIndexPatternFields(indexPatternFields);
Expand Down Expand Up @@ -282,7 +281,7 @@ describe('Field editor Preview panel', () => {
toggleFormRow,
fields,
waitForUpdates,
getLatestPreviewHttpRequest,
// getLatestPreviewHttpRequest,
getRenderedFieldsPreview,
},
} = testBed;
Expand All @@ -291,10 +290,12 @@ describe('Field editor Preview panel', () => {
await fields.updateName('myRuntimeField');
await fields.updateScript('echo("hello")');
await waitForUpdates(); // Run validations
const request = getLatestPreviewHttpRequest(server);
// todo might not need anymore
// const request = getLatestPreviewHttpRequest(server);

// Make sure the payload sent is correct
expect(request.requestBody).toEqual({
console.log('checking calls');
expect(server.post.mock.calls[0]).toEqual({
context: 'keyword_field',
document: {
description: 'First doc - description',
Expand Down Expand Up @@ -373,8 +374,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;
// server.respondImmediately = false;
// server.autoRespond = false;

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

Expand All @@ -394,7 +395,7 @@ describe('Field editor Preview panel', () => {
await fields.updateScript('echo("hello")');
expect(exists('isUpdatingIndicator')).toBe(true); // indicator while getting preview

server.respond();
// server.respond();
await waitForUpdates();
expect(exists('isUpdatingIndicator')).toBe(false);
});
Expand All @@ -403,8 +404,8 @@ describe('Field editor Preview panel', () => {
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] });
// 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;
// server.respondImmediately = false;
// server.autoRespond = false;

const {
exists,
Expand All @@ -417,7 +418,7 @@ describe('Field editor Preview panel', () => {
await fields.updateScript('echo("hello")');
expect(exists('isUpdatingIndicator')).toBe(true);

server.respond();
// server.respond();
await waitForDocumentsAndPreviewUpdate();

expect(exists('isUpdatingIndicator')).toBe(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,52 @@
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
) => {
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) => {
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]);
});
};
return {
setFieldPreviewResponse,
};
};

// Register helpers to mock HTTP Requests
/*
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>,
shouldDelayResponse: () => boolean
) => {
const setFieldPreviewResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.body.status || 400 : 200;
Expand All @@ -30,8 +71,10 @@ const registerHttpRequestMockHelpers = (
setFieldPreviewResponse,
};
};
*/

export const init = () => {
/*
const server = sinon.fakeServer.create();
server.respondImmediately = true;
Expand All @@ -41,9 +84,20 @@ export const init = () => {
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);

return {
server,
httpSetup,
setDelayResponse,
httpRequestsMockHelpers,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@ let apiService: ApiService;

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

return {
server,
server: httpSetup,
httpRequestsMockHelpers,
};
};
Expand Down

0 comments on commit ce900bc

Please sign in to comment.