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

Removing axios from data_view_field_editor test #129116

Merged
merged 9 commits into from
Apr 11, 2022
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
} 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 @@ -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,9 +54,6 @@ describe('Field editor Preview panel', () => {
];

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

httpRequestsMockHelpers.setFieldPreviewResponse({ values: ['mockedScriptValue'] });
setIndexPatternFields(indexPatternFields);
setSearchResponse(mockDocuments);
Expand Down Expand Up @@ -278,23 +274,18 @@ describe('Field editor Preview panel', () => {
httpRequestsMockHelpers.setFieldPreviewResponse({ values: [scriptEmitResponse] });

const {
actions: {
toggleFormRow,
fields,
waitForUpdates,
getLatestPreviewHttpRequest,
getRenderedFieldsPreview,
},
actions: { toggleFormRow, fields, waitForUpdates, getRenderedFieldsPreview },
} = testBed;

await toggleFormRow('value');
await fields.updateName('myRuntimeField');
await fields.updateScript('echo("hello")');
await waitForUpdates(); // Run validations
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 Down Expand Up @@ -373,10 +364,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 @@ -394,17 +383,14 @@ describe('Field editor Preview panel', () => {
await fields.updateScript('echo("hello")');
expect(exists('isUpdatingIndicator')).toBe(true); // indicator while getting preview

server.respond();
await waitForUpdates();
expect(exists('isUpdatingIndicator')).toBe(false);
});

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 All @@ -417,7 +403,6 @@ describe('Field editor Preview panel', () => {
await fields.updateScript('echo("hello")');
expect(exists('isUpdatingIndicator')).toBe(true);

server.respond();
await waitForDocumentsAndPreviewUpdate();

expect(exists('isUpdatingIndicator')).toBe(false);
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 @@ -10,8 +10,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 @@ -23,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 = axios.create({ adapter: axiosXhrAdapter });
const dataStart = dataPluginMock.createStartContract();
const { search } = dataStart;

Expand Down Expand Up @@ -61,12 +58,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