Skip to content

Commit

Permalink
[7.17] Removing axios from data_view_field_editor test (elastic#129116)…
Browse files Browse the repository at this point in the history
… (elastic#129952)

* Removing axios from data_view_field_editor test  (elastic#129116)

* test bed fixes
Co-authored-by: Kibana Machine <[email protected]>

(cherry picked from commit ae39e1b)

# Conflicts:
#	src/plugins/data_view_field_editor/__jest__/client_integration/field_editor.test.tsx
#	src/plugins/data_view_field_editor/__jest__/client_integration/field_editor_flyout_content.test.ts
#	src/plugins/data_view_field_editor/__jest__/client_integration/field_editor_flyout_preview.test.ts
#	src/plugins/data_view_field_editor/__jest__/client_integration/helpers/setup_environment.tsx

* better match main pr

* fix integration test
  • Loading branch information
mattkime authored Apr 13, 2022
1 parent e5d6973 commit a80fc36
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import type { RuntimeFieldPainlessError } from '../../public/lib';
import { setup, FieldEditorTestBed, defaultProps } from './field_editor.helpers';

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

let testBed: FieldEditorTestBed;
let onChange: jest.Mock<Props['onChange']> = jest.fn();
Expand Down Expand Up @@ -70,7 +70,6 @@ describe('<FieldEditor />', () => {

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

beforeEach(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { setupEnvironment } from './helpers';
import { setup } from './field_editor_flyout_content.helpers';

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

beforeAll(() => {
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['foo'] });
Expand All @@ -21,7 +21,6 @@ describe('<FieldEditorFlyoutContent />', () => {

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

test('should have the correct title', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ describe('Field editor Preview panel', () => {

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

let testBed: FieldEditorFlyoutContentTestBed;
Expand Down Expand Up @@ -346,20 +345,20 @@ describe('Field editor Preview panel', () => {
actions: {
toggleFormRow,
fields,
waitForDocumentsAndPreviewUpdate,
getLatestPreviewHttpRequest,
getRenderedFieldsPreview,
waitForDocumentsAndPreviewUpdate,
},
} = testBed;

await toggleFormRow('value');
await fields.updateName('myRuntimeField');
await fields.updateScript('echo("hello")');
await waitForDocumentsAndPreviewUpdate();
const request = getLatestPreviewHttpRequest(server);

// Make sure the payload sent is correct
expect(request.requestBody).toEqual({
const firstCall = server.post.mock.calls[0] as Array<{ body: any }>;
const payload = JSON.parse(firstCall[1]?.body);
expect(payload).toEqual({
context: 'keyword_field',
document: {
description: 'First doc - description',
Expand All @@ -380,7 +379,7 @@ describe('Field editor Preview panel', () => {
});

test('should display an updating indicator while fetching the preview', async () => {
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] });
httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['ok'] }, undefined, true);

const {
exists,
Expand All @@ -399,7 +398,7 @@ 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);

const {
exists,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,37 @@
* Side Public License, v 1.
*/

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

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

// Register helpers to mock HTTP Requests
const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
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,
]);
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>
) => {
const setFieldPreviewResponse = (response?: HttpResponse, error?: any, delayResponse = false) => {
const body = error ? JSON.stringify(error.body) : response;

httpSetup.post.mockImplementation(() => {
if (delayResponse) {
return new Promise((resolve) => {
setTimeout(() => resolve({ data: body }), 1000);
});
} else {
return Promise.resolve({ data: 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);
const httpSetup = httpServiceMock.createSetupContract();
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup);

return {
server,
httpSetup,
httpRequestsMockHelpers,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
import './jest.mocks';

import React, { FunctionComponent } from 'react';
import axios from 'axios';
import axiosXhrAdapter from 'axios/lib/adapters/xhr';
import { merge } from 'lodash';

import { notificationServiceMock, uiSettingsServiceMock } from '../../../../../core/public/mocks';
Expand All @@ -20,7 +18,6 @@ import { FieldPreviewProvider } from '../../../public/components/preview';
import { initApi, ApiService } from '../../../public/lib';
import { init as initHttpRequests } from './http_requests';

const mockHttpClient = axios.create({ adapter: axiosXhrAdapter });
const dataStart = dataPluginMock.createStartContract();
const { search, fieldFormats } = dataStart;

Expand All @@ -44,12 +41,11 @@ search.search = spySearchQuery;
let apiService: ApiService;

export const setupEnvironment = () => {
// @ts-expect-error Axios does not fullfill HttpSetupn from core but enough for our tests
apiService = initApi(mockHttpClient);
const { server, httpRequestsMockHelpers } = initHttpRequests();
const { httpSetup, httpRequestsMockHelpers } = initHttpRequests();
apiService = initApi(httpSetup);

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

0 comments on commit a80fc36

Please sign in to comment.