Skip to content

Commit

Permalink
[Lens] cleanup divide mock file to smaller pieces (elastic#115925)
Browse files Browse the repository at this point in the history
Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
2 people authored and shivindera committed Oct 25, 2021
1 parent 7ed001c commit ad0a9ff
Show file tree
Hide file tree
Showing 9 changed files with 635 additions and 540 deletions.
540 changes: 0 additions & 540 deletions x-pack/plugins/lens/public/mocks.tsx

This file was deleted.

122 changes: 122 additions & 0 deletions x-pack/plugins/lens/public/mocks/data_plugin_mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { Observable, Subject } from 'rxjs';
import moment from 'moment';
import { DataPublicPluginStart, esFilters } from '../../../../../src/plugins/data/public';

function createMockTimefilter() {
const unsubscribe = jest.fn();

let timeFilter = { from: 'now-7d', to: 'now' };
let subscriber: () => void;
return {
getTime: jest.fn(() => timeFilter),
setTime: jest.fn((newTimeFilter) => {
timeFilter = newTimeFilter;
if (subscriber) {
subscriber();
}
}),
getTimeUpdate$: () => ({
subscribe: ({ next }: { next: () => void }) => {
subscriber = next;
return unsubscribe;
},
}),
calculateBounds: jest.fn(() => ({
min: moment('2021-01-10T04:00:00.000Z'),
max: moment('2021-01-10T08:00:00.000Z'),
})),
getBounds: jest.fn(() => timeFilter),
getRefreshInterval: () => {},
getRefreshIntervalDefaults: () => {},
getAutoRefreshFetch$: () => new Observable(),
};
}

export function mockDataPlugin(
sessionIdSubject = new Subject<string>(),
initialSessionId?: string
) {
function createMockSearchService() {
let sessionIdCounter = initialSessionId ? 1 : 0;
let currentSessionId: string | undefined = initialSessionId;
const start = () => {
currentSessionId = `sessionId-${++sessionIdCounter}`;
return currentSessionId;
};
return {
session: {
start: jest.fn(start),
clear: jest.fn(),
getSessionId: jest.fn(() => currentSessionId),
getSession$: jest.fn(() => sessionIdSubject.asObservable()),
},
};
}

function createMockFilterManager() {
const unsubscribe = jest.fn();

let subscriber: () => void;
let filters: unknown = [];

return {
getUpdates$: () => ({
subscribe: ({ next }: { next: () => void }) => {
subscriber = next;
return unsubscribe;
},
}),
setFilters: jest.fn((newFilters: unknown[]) => {
filters = newFilters;
if (subscriber) subscriber();
}),
setAppFilters: jest.fn((newFilters: unknown[]) => {
filters = newFilters;
if (subscriber) subscriber();
}),
getFilters: () => filters,
getGlobalFilters: () => {
// @ts-ignore
return filters.filter(esFilters.isFilterPinned);
},
removeAll: () => {
filters = [];
subscriber();
},
};
}
function createMockQueryString() {
return {
getQuery: jest.fn(() => ({ query: '', language: 'lucene' })),
setQuery: jest.fn(),
getDefaultQuery: jest.fn(() => ({ query: '', language: 'lucene' })),
};
}
return {
query: {
filterManager: createMockFilterManager(),
timefilter: {
timefilter: createMockTimefilter(),
},
queryString: createMockQueryString(),
state$: new Observable(),
},
indexPatterns: {
get: jest.fn().mockImplementation((id) => Promise.resolve({ id, isTimeBased: () => true })),
},
search: createMockSearchService(),
nowProvider: {
get: jest.fn(),
},
fieldFormats: {
deserialize: jest.fn(),
},
} as unknown as DataPublicPluginStart;
}
78 changes: 78 additions & 0 deletions x-pack/plugins/lens/public/mocks/datasource_mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { DatasourcePublicAPI, Datasource } from '../types';

export type DatasourceMock = jest.Mocked<Datasource> & {
publicAPIMock: jest.Mocked<DatasourcePublicAPI>;
};

export function createMockDatasource(id: string): DatasourceMock {
const publicAPIMock: jest.Mocked<DatasourcePublicAPI> = {
datasourceId: id,
getTableSpec: jest.fn(() => []),
getOperationForColumnId: jest.fn(),
};

return {
id: 'testDatasource',
clearLayer: jest.fn((state, _layerId) => state),
getDatasourceSuggestionsForField: jest.fn((_state, _item, filterFn) => []),
getDatasourceSuggestionsForVisualizeField: jest.fn((_state, _indexpatternId, _fieldName) => []),
getDatasourceSuggestionsFromCurrentState: jest.fn((_state) => []),
getPersistableState: jest.fn((x) => ({
state: x,
savedObjectReferences: [{ type: 'index-pattern', id: 'mockip', name: 'mockip' }],
})),
getPublicAPI: jest.fn().mockReturnValue(publicAPIMock),
initialize: jest.fn((_state?) => Promise.resolve()),
renderDataPanel: jest.fn(),
renderLayerPanel: jest.fn(),
toExpression: jest.fn((_frame, _state) => null),
insertLayer: jest.fn((_state, _newLayerId) => ({})),
removeLayer: jest.fn((_state, _layerId) => {}),
removeColumn: jest.fn((props) => {}),
getLayers: jest.fn((_state) => []),
uniqueLabels: jest.fn((_state) => ({})),
renderDimensionTrigger: jest.fn(),
renderDimensionEditor: jest.fn(),
getDropProps: jest.fn(),
onDrop: jest.fn(),

// this is an additional property which doesn't exist on real datasources
// but can be used to validate whether specific API mock functions are called
publicAPIMock,
getErrorMessages: jest.fn((_state) => undefined),
checkIntegrity: jest.fn((_state) => []),
isTimeBased: jest.fn(),
isValidColumn: jest.fn(),
};
}

export function mockDatasourceMap() {
const datasource = createMockDatasource('testDatasource');
datasource.getDatasourceSuggestionsFromCurrentState.mockReturnValue([
{
state: {},
table: {
columns: [],
isMultiRow: true,
layerId: 'a',
changeType: 'unchanged',
},
keptLayerIds: ['a'],
},
]);

datasource.getLayers.mockReturnValue(['a']);
return {
testDatasource2: createMockDatasource('testDatasource2'),
testDatasource: datasource,
};
}

export const datasourceMap = mockDatasourceMap();
16 changes: 16 additions & 0 deletions x-pack/plugins/lens/public/mocks/expression_renderer_mock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { ReactExpressionRendererProps } from 'src/plugins/expressions/public';

export function createExpressionRendererMock(): jest.Mock<
React.ReactElement,
[ReactExpressionRendererProps]
> {
return jest.fn((_) => <span />);
}
42 changes: 42 additions & 0 deletions x-pack/plugins/lens/public/mocks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { FramePublicAPI, FrameDatasourceAPI } from '../types';
export { mockDataPlugin } from './data_plugin_mock';
export {
visualizationMap,
createMockVisualization,
mockVisualizationMap,
} from './visualization_mock';
export { datasourceMap, mockDatasourceMap, createMockDatasource } from './datasource_mock';
export type { DatasourceMock } from './datasource_mock';
export { createExpressionRendererMock } from './expression_renderer_mock';
export { defaultDoc, exactMatchDoc, makeDefaultServices } from './services_mock';
export {
mockStoreDeps,
mockDatasourceStates,
defaultState,
makeLensStore,
MountStoreProps,
mountWithProvider,
} from './store_mocks';
export { lensPluginMock } from './lens_plugin_mock';

export type FrameMock = jest.Mocked<FramePublicAPI>;

export const createMockFramePublicAPI = (): FrameMock => ({
datasourceLayers: {},
});

export type FrameDatasourceMock = jest.Mocked<FrameDatasourceAPI>;

export const createMockFrameDatasourceAPI = (): FrameDatasourceMock => ({
datasourceLayers: {},
dateRange: { fromDate: 'now-7d', toDate: 'now' },
query: { query: '', language: 'lucene' },
filters: [],
});
31 changes: 31 additions & 0 deletions x-pack/plugins/lens/public/mocks/lens_plugin_mock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { LensPublicStart } from '..';
import { visualizationTypes } from '../xy_visualization/types';

type Start = jest.Mocked<LensPublicStart>;

export const lensPluginMock = {
createStartContract: (): Start => {
const startContract: Start = {
EmbeddableComponent: jest.fn(() => {
return <span>Lens Embeddable Component</span>;
}),
SaveModalComponent: jest.fn(() => {
return <span>Lens Save Modal Component</span>;
}),
canUseEditor: jest.fn(() => true),
navigateToPrefilledEditor: jest.fn(),
getXyVisTypes: jest
.fn()
.mockReturnValue(new Promise((resolve) => resolve(visualizationTypes))),
};
return startContract;
},
};
Loading

0 comments on commit ad0a9ff

Please sign in to comment.