From 3186657be3422512bad7b67821f313c8d173a5b7 Mon Sep 17 00:00:00 2001 From: Dzmitry Tamashevich Date: Fri, 4 Nov 2022 13:56:18 +0300 Subject: [PATCH 1/3] [Discover] fix dashboard tests --- x-pack/plugins/lens/public/plugin.ts | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/x-pack/plugins/lens/public/plugin.ts b/x-pack/plugins/lens/public/plugin.ts index 8a12a58f16087..e995bfe319e82 100644 --- a/x-pack/plugins/lens/public/plugin.ts +++ b/x-pack/plugins/lens/public/plugin.ts @@ -317,18 +317,14 @@ export class LensPlugin { visualizations.registerAlias(getLensAliasConfig()); - const discoverLocator = share?.url.locators.get('DISCOVER_APP_LOCATOR'); - - if (discoverLocator) { - uiActionsEnhanced.registerDrilldown( - new OpenInDiscoverDrilldown({ - dataViews: () => this.dataViewsService!, - locator: () => discoverLocator, - hasDiscoverAccess: () => this.hasDiscoverAccess, - application: () => startServices().core.application, - }) - ); - } + uiActionsEnhanced.registerDrilldown( + new OpenInDiscoverDrilldown({ + dataViews: () => this.dataViewsService!, + locator: () => share?.url.locators.get('DISCOVER_APP_LOCATOR'), + hasDiscoverAccess: () => this.hasDiscoverAccess, + application: () => startServices().core.application, + }) + ); setupExpressions( expressions, @@ -500,7 +496,6 @@ export class LensPlugin { ); const discoverLocator = startDependencies.share?.url.locators.get('DISCOVER_APP_LOCATOR'); - if (discoverLocator) { startDependencies.uiActions.addTriggerAction( CONTEXT_MENU_TRIGGER, From 3e4418b1fe67b9695d2033c835d1c53458826bdf Mon Sep 17 00:00:00 2001 From: Dzmitry Tamashevich Date: Fri, 4 Nov 2022 16:34:24 +0300 Subject: [PATCH 2/3] [Discover] fix jest tests --- .../__mocks__/data_view_with_timefield.ts | 5 ++ .../discover/public/__mocks__/services.ts | 1 + .../layout/discover_layout.test.tsx | 83 ++++-------------- .../layout/discover_main_content.test.tsx | 83 ++++-------------- .../layout/use_discover_histogram.test.ts | 84 +------------------ .../__mocks__/data_view_with_timefield.ts | 6 ++ .../public/__mocks__/services.ts | 1 + .../public/chart/chart.test.tsx | 53 +++--------- 8 files changed, 60 insertions(+), 256 deletions(-) diff --git a/src/plugins/discover/public/__mocks__/data_view_with_timefield.ts b/src/plugins/discover/public/__mocks__/data_view_with_timefield.ts index 803fb7c6f70db..a481c648aad20 100644 --- a/src/plugins/discover/public/__mocks__/data_view_with_timefield.ts +++ b/src/plugins/discover/public/__mocks__/data_view_with_timefield.ts @@ -18,6 +18,7 @@ const fields = [ }, { name: 'timestamp', + displayName: 'timestamp', type: 'date', scripted: false, filterable: true, @@ -26,12 +27,14 @@ const fields = [ }, { name: 'message', + displayName: 'message', type: 'string', scripted: false, filterable: false, }, { name: 'extension', + displayName: 'extension', type: 'string', scripted: false, filterable: true, @@ -39,6 +42,7 @@ const fields = [ }, { name: 'bytes', + displayName: 'bytes', type: 'number', scripted: false, filterable: true, @@ -46,6 +50,7 @@ const fields = [ }, { name: 'scripted', + displayName: 'scripted', type: 'number', scripted: true, filterable: false, diff --git a/src/plugins/discover/public/__mocks__/services.ts b/src/plugins/discover/public/__mocks__/services.ts index 97de63d231a46..c6b307098c1a8 100644 --- a/src/plugins/discover/public/__mocks__/services.ts +++ b/src/plugins/discover/public/__mocks__/services.ts @@ -126,4 +126,5 @@ export const discoverServiceMock = { savedObjectsTagging: {}, dataViews: dataViewsMock, timefilter: { createFilter: jest.fn() }, + lens: { EmbeddableComponent: jest.fn(() => null) }, } as unknown as DiscoverServices; diff --git a/src/plugins/discover/public/application/main/components/layout/discover_layout.test.tsx b/src/plugins/discover/public/application/main/components/layout/discover_layout.test.tsx index 0e9c7f8449520..0a76d979c71f8 100644 --- a/src/plugins/discover/public/application/main/components/layout/discover_layout.test.tsx +++ b/src/plugins/discover/public/application/main/components/layout/discover_layout.test.tsx @@ -7,7 +7,7 @@ */ import React from 'react'; -import { Subject, BehaviorSubject } from 'rxjs'; +import { Subject, BehaviorSubject, of } from 'rxjs'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import type { Query, AggregateQuery } from '@kbn/es-query'; import { setHeaderActionMenuMounter } from '../../../../kibana_services'; @@ -15,14 +15,16 @@ import { DiscoverLayout, SIDEBAR_CLOSED_KEY } from './discover_layout'; import { esHits } from '../../../../__mocks__/es_hits'; import { dataViewMock } from '../../../../__mocks__/data_view'; import { savedSearchMock } from '../../../../__mocks__/saved_search'; -import { createSearchSourceMock } from '@kbn/data-plugin/common/search/search_source/mocks'; +import { + createSearchSourceMock, + searchSourceInstanceMock, +} from '@kbn/data-plugin/common/search/search_source/mocks'; import type { DataView } from '@kbn/data-views-plugin/public'; import { dataViewWithTimefieldMock } from '../../../../__mocks__/data_view_with_timefield'; import { GetStateReturn } from '../../services/discover_state'; import { DiscoverLayoutProps } from './types'; import { AvailableFields$, - DataCharts$, DataDocuments$, DataMain$, DataTotalHits$, @@ -37,66 +39,10 @@ import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { DiscoverServices } from '../../../../build_services'; import { buildDataTableRecord } from '../../../../utils/build_data_record'; import { DiscoverAppStateProvider } from '../../services/discover_app_state_container'; -import type { UnifiedHistogramChartData } from '@kbn/unified-histogram-plugin/public'; import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock'; -import type { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { setTimeout } from 'timers/promises'; import { act } from 'react-dom/test-utils'; - -jest.mock('@kbn/unified-histogram-plugin/public', () => { - const originalModule = jest.requireActual('@kbn/unified-histogram-plugin/public'); - - const chartData = { - xAxisOrderedValues: [ - 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, - 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, - 1624917600000, 1625004000000, 1625090400000, - ], - xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, - xAxisLabel: 'order_date per day', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: { - asMilliseconds: jest.fn(), - }, - intervalESUnit: 'd', - intervalESValue: 1, - min: '2021-03-18T08:28:56.411Z', - max: '2021-07-01T07:28:56.411Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1623880800000, y: 134 }, - { x: 1623967200000, y: 152 }, - { x: 1624053600000, y: 141 }, - { x: 1624140000000, y: 138 }, - { x: 1624226400000, y: 142 }, - { x: 1624312800000, y: 157 }, - { x: 1624399200000, y: 149 }, - { x: 1624485600000, y: 146 }, - { x: 1624572000000, y: 170 }, - { x: 1624658400000, y: 137 }, - { x: 1624744800000, y: 150 }, - { x: 1624831200000, y: 144 }, - { x: 1624917600000, y: 147 }, - { x: 1625004000000, y: 137 }, - { x: 1625090400000, y: 66 }, - ], - } as unknown as UnifiedHistogramChartData; - - return { - ...originalModule, - buildChartData: jest.fn().mockImplementation(() => ({ - chartData, - bucketInterval: { - scaled: true, - description: 'test', - scale: 2, - }, - })), - }; -}); +import { createSearchSessionMock } from '../../../../__mocks__/search_session'; function getAppStateContainer() { const appStateContainer = getDiscoverStateMock({ isTimeBased: true }).appStateContainer; @@ -127,6 +73,14 @@ async function mountComponent( return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' }; }; + (services.data.query.queryString.getDefaultQuery as jest.Mock).mockReturnValue({ + language: 'kuery', + query: '', + }); + (searchSourceInstanceMock.fetch$ as jest.Mock).mockImplementation( + jest.fn().mockReturnValue(of({ rawResponse: { hits: { total: 2 } } })) + ); + const dataViewList = [dataView]; const main$ = new BehaviorSubject({ @@ -150,16 +104,10 @@ async function mountComponent( result: Number(esHits.length), }) as DataTotalHits$; - const charts$ = new BehaviorSubject({ - fetchStatus: FetchStatus.COMPLETE, - response: {} as unknown as SearchResponse, - }) as DataCharts$; - const savedSearchData$ = { main$, documents$, totalHits$, - charts$, availableFields$, }; @@ -175,7 +123,7 @@ async function mountComponent( savedSearchData$, savedSearchRefetch$: new Subject(), searchSource: searchSourceMock, - state: { columns: [], query }, + state: { columns: [], query, hideChart: false, interval: 'auto' }, stateContainer: { setAppState: () => {}, appStateContainer: { @@ -188,6 +136,7 @@ async function mountComponent( persistDataView: jest.fn(), updateAdHocDataViewId: jest.fn(), adHocDataViewList: [], + searchSessionManager: createSearchSessionMock().searchSessionManager, }; const component = mountWithIntl( diff --git a/src/plugins/discover/public/application/main/components/layout/discover_main_content.test.tsx b/src/plugins/discover/public/application/main/components/layout/discover_main_content.test.tsx index 54e3fa0b19ca5..7d94bd86ec842 100644 --- a/src/plugins/discover/public/application/main/components/layout/discover_main_content.test.tsx +++ b/src/plugins/discover/public/application/main/components/layout/discover_main_content.test.tsx @@ -7,7 +7,7 @@ */ import React from 'react'; -import { Subject, BehaviorSubject } from 'rxjs'; +import { Subject, BehaviorSubject, of } from 'rxjs'; import { findTestSubject, mountWithIntl } from '@kbn/test-jest-helpers'; import { esHits } from '../../../../__mocks__/es_hits'; import { dataViewMock } from '../../../../__mocks__/data_view'; @@ -15,7 +15,6 @@ import { savedSearchMock } from '../../../../__mocks__/saved_search'; import { GetStateReturn } from '../../services/discover_state'; import { AvailableFields$, - DataCharts$, DataDocuments$, DataMain$, DataTotalHits$, @@ -33,67 +32,11 @@ import { setTimeout } from 'timers/promises'; import { DocumentViewModeToggle } from '../../../../components/view_mode_toggle'; import { Storage } from '@kbn/kibana-utils-plugin/public'; import { LocalStorageMock } from '../../../../__mocks__/local_storage_mock'; -import { - UnifiedHistogramChartData, - UnifiedHistogramLayout, -} from '@kbn/unified-histogram-plugin/public'; +import { UnifiedHistogramLayout } from '@kbn/unified-histogram-plugin/public'; import { HISTOGRAM_HEIGHT_KEY } from './use_discover_histogram'; -import type { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; - -jest.mock('@kbn/unified-histogram-plugin/public', () => { - const originalModule = jest.requireActual('@kbn/unified-histogram-plugin/public'); - - const chartData = { - xAxisOrderedValues: [ - 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, - 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, - 1624917600000, 1625004000000, 1625090400000, - ], - xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, - xAxisLabel: 'order_date per day', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: { - asMilliseconds: jest.fn(), - }, - intervalESUnit: 'd', - intervalESValue: 1, - min: '2021-03-18T08:28:56.411Z', - max: '2021-07-01T07:28:56.411Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1623880800000, y: 134 }, - { x: 1623967200000, y: 152 }, - { x: 1624053600000, y: 141 }, - { x: 1624140000000, y: 138 }, - { x: 1624226400000, y: 142 }, - { x: 1624312800000, y: 157 }, - { x: 1624399200000, y: 149 }, - { x: 1624485600000, y: 146 }, - { x: 1624572000000, y: 170 }, - { x: 1624658400000, y: 137 }, - { x: 1624744800000, y: 150 }, - { x: 1624831200000, y: 144 }, - { x: 1624917600000, y: 147 }, - { x: 1625004000000, y: 137 }, - { x: 1625090400000, y: 66 }, - ], - } as unknown as UnifiedHistogramChartData; - - return { - ...originalModule, - buildChartData: jest.fn().mockImplementation(() => ({ - chartData, - bucketInterval: { - scaled: true, - description: 'test', - scale: 2, - }, - })), - }; -}); +import { createSearchSessionMock } from '../../../../__mocks__/search_session'; +import { RequestAdapter } from '@kbn/inspector-plugin/public'; +import { searchSourceInstanceMock } from '@kbn/data-plugin/common/search/search_source/mocks'; const mountComponent = async ({ isPlainRecord = false, @@ -115,6 +58,14 @@ const mountComponent = async ({ return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' }; }; + (services.data.query.queryString.getDefaultQuery as jest.Mock).mockReturnValue({ + language: 'kuery', + query: '', + }); + (searchSourceInstanceMock.fetch$ as jest.Mock).mockImplementation( + jest.fn().mockReturnValue(of({ rawResponse: { hits: { total: 2 } } })) + ); + if (storage) { services = { ...services, storage }; } @@ -140,16 +91,10 @@ const mountComponent = async ({ result: Number(esHits.length), }) as DataTotalHits$; - const charts$ = new BehaviorSubject({ - fetchStatus: FetchStatus.COMPLETE, - response: {} as unknown as SearchResponse, - }) as DataCharts$; - const savedSearchData$ = { main$, documents$, totalHits$, - charts$, availableFields$, }; @@ -177,6 +122,8 @@ const mountComponent = async ({ onFieldEdited: jest.fn(), columns: [], resizeRef: { current: null }, + searchSessionManager: createSearchSessionMock().searchSessionManager, + inspectorAdapters: { requests: new RequestAdapter() }, }; const coreTheme$ = new BehaviorSubject({ darkMode: false }); diff --git a/src/plugins/discover/public/application/main/components/layout/use_discover_histogram.test.ts b/src/plugins/discover/public/application/main/components/layout/use_discover_histogram.test.ts index 12fde6a5b1061..59b2e0492f62b 100644 --- a/src/plugins/discover/public/application/main/components/layout/use_discover_histogram.test.ts +++ b/src/plugins/discover/public/application/main/components/layout/use_discover_histogram.test.ts @@ -6,7 +6,6 @@ * Side Public License, v 1. */ -import type { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { buildDataTableRecord } from '../../../../utils/build_data_record'; import { esHits } from '../../../../__mocks__/es_hits'; import { act, renderHook } from '@testing-library/react-hooks'; @@ -14,7 +13,6 @@ import { BehaviorSubject } from 'rxjs'; import { FetchStatus } from '../../../types'; import { AvailableFields$, - DataCharts$, DataDocuments$, DataMain$, DataTotalHits$, @@ -33,6 +31,8 @@ import { } from './use_discover_histogram'; import { setTimeout } from 'timers/promises'; import { calculateBounds } from '@kbn/data-plugin/public'; +import { createSearchSessionMock } from '../../../../__mocks__/search_session'; +import { RequestAdapter } from '@kbn/inspector-plugin/public'; const mockData = dataPluginMock.createStartContract(); @@ -100,61 +100,10 @@ describe('useDiscoverHistogram', () => { result: Number(esHits.length), }) as DataTotalHits$; - const charts$ = new BehaviorSubject({ - fetchStatus: FetchStatus.COMPLETE, - response: { - took: 0, - timed_out: false, - _shards: { - total: 1, - successful: 1, - skipped: 0, - failed: 0, - }, - hits: { - total: 29, - max_score: null, - hits: [], - }, - aggregations: { - '2': { - buckets: [ - { - key_as_string: '2022-10-05T16:00:00.000-03:00', - key: 1664996400000, - doc_count: 6, - }, - { - key_as_string: '2022-10-05T16:30:00.000-03:00', - key: 1664998200000, - doc_count: 2, - }, - { - key_as_string: '2022-10-05T17:00:00.000-03:00', - key: 1665000000000, - doc_count: 3, - }, - { - key_as_string: '2022-10-05T17:30:00.000-03:00', - key: 1665001800000, - doc_count: 8, - }, - { - key_as_string: '2022-10-05T18:00:00.000-03:00', - key: 1665003600000, - doc_count: 10, - }, - ], - }, - }, - } as SearchResponse, - }) as DataCharts$; - const savedSearchData$ = { main$, documents$, totalHits$, - charts$, availableFields$, }; @@ -167,6 +116,8 @@ describe('useDiscoverHistogram', () => { savedSearch: savedSearchMock, isTimeBased, isPlainRecord, + inspectorAdapters: { requests: new RequestAdapter() }, + searchSessionManager: createSearchSessionMock().searchSessionManager, }); }); @@ -175,29 +126,6 @@ describe('useDiscoverHistogram', () => { return hook; }; - const expectedChartData = { - xAxisOrderedValues: [1664996400000, 1664998200000, 1665000000000, 1665001800000, 1665003600000], - xAxisFormat: { id: 'date', params: { pattern: 'HH:mm:ss.SSS' } }, - xAxisLabel: 'timestamp per 0 milliseconds', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: 'P0D', - intervalESUnit: 'ms', - intervalESValue: 0, - min: '1991-03-29T08:04:00.694Z', - max: '2021-03-29T07:04:00.695Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1664996400000, y: 6 }, - { x: 1664998200000, y: 2 }, - { x: 1665000000000, y: 3 }, - { x: 1665001800000, y: 8 }, - { x: 1665003600000, y: 10 }, - ], - }; - describe('contexts', () => { it('should output the correct hits context', async () => { const { result } = await renderUseDiscoverHistogram(); @@ -207,12 +135,8 @@ describe('useDiscoverHistogram', () => { it('should output the correct chart context', async () => { const { result } = await renderUseDiscoverHistogram(); - expect(result.current.chart?.status).toBe(FetchStatus.COMPLETE); expect(result.current.chart?.hidden).toBe(false); expect(result.current.chart?.timeInterval).toBe('auto'); - expect(result.current.chart?.bucketInterval?.toString()).toBe('P0D'); - expect(JSON.stringify(result.current.chart?.data)).toBe(JSON.stringify(expectedChartData)); - expect(result.current.chart?.error).toBeUndefined(); }); it('should output undefined for hits and chart if isPlainRecord is true', async () => { diff --git a/src/plugins/unified_histogram/public/__mocks__/data_view_with_timefield.ts b/src/plugins/unified_histogram/public/__mocks__/data_view_with_timefield.ts index 158d697d67c71..b0ec2fcf84ebb 100644 --- a/src/plugins/unified_histogram/public/__mocks__/data_view_with_timefield.ts +++ b/src/plugins/unified_histogram/public/__mocks__/data_view_with_timefield.ts @@ -12,12 +12,14 @@ import { buildDataViewMock } from './data_view'; const fields = [ { name: '_index', + displayName: '_index', type: 'string', scripted: false, filterable: true, }, { name: 'timestamp', + displayName: 'timestamp', type: 'date', scripted: false, filterable: true, @@ -26,12 +28,14 @@ const fields = [ }, { name: 'message', + displayName: 'message', type: 'string', scripted: false, filterable: false, }, { name: 'extension', + displayName: 'extension', type: 'string', scripted: false, filterable: true, @@ -39,6 +43,7 @@ const fields = [ }, { name: 'bytes', + displayName: 'bytes', type: 'number', scripted: false, filterable: true, @@ -46,6 +51,7 @@ const fields = [ }, { name: 'scripted', + displayName: 'scripted', type: 'number', scripted: true, filterable: false, diff --git a/src/plugins/unified_histogram/public/__mocks__/services.ts b/src/plugins/unified_histogram/public/__mocks__/services.ts index e827596d88feb..1ce16ad8fae85 100644 --- a/src/plugins/unified_histogram/public/__mocks__/services.ts +++ b/src/plugins/unified_histogram/public/__mocks__/services.ts @@ -25,4 +25,5 @@ export const unifiedHistogramServicesMock = { useChartsTheme: jest.fn(() => EUI_CHARTS_THEME_LIGHT.theme), useChartsBaseTheme: jest.fn(() => EUI_CHARTS_THEME_LIGHT.theme), }, + lens: { EmbeddableComponent: jest.fn(() => null) }, } as unknown as UnifiedHistogramServices; diff --git a/src/plugins/unified_histogram/public/chart/chart.test.tsx b/src/plugins/unified_histogram/public/chart/chart.test.tsx index 41de0687acfa6..80d3a37d0c27b 100644 --- a/src/plugins/unified_histogram/public/chart/chart.test.tsx +++ b/src/plugins/unified_histogram/public/chart/chart.test.tsx @@ -9,11 +9,14 @@ import React, { ReactElement } from 'react'; import { act } from 'react-dom/test-utils'; import { mountWithIntl } from '@kbn/test-jest-helpers'; -import type { UnifiedHistogramChartData, UnifiedHistogramFetchStatus } from '../types'; +import type { UnifiedHistogramFetchStatus } from '../types'; import { Chart } from './chart'; import type { ReactWrapper } from 'enzyme'; import { unifiedHistogramServicesMock } from '../__mocks__/services'; +import { searchSourceInstanceMock } from '@kbn/data-plugin/common/search/search_source/mocks'; +import { of } from 'rxjs'; import { HitsCounter } from '../hits_counter'; +import { dataViewWithTimefieldMock } from '../__mocks__/data_view_with_timefield'; async function mountComponent({ noChart, @@ -32,47 +35,16 @@ async function mountComponent({ services.data.query.timefilter.timefilter.getAbsoluteTime = () => { return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' }; }; - - const chartData = { - xAxisOrderedValues: [ - 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, - 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, - 1624917600000, 1625004000000, 1625090400000, - ], - xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, - xAxisLabel: 'order_date per day', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: { - asMilliseconds: jest.fn(), - }, - intervalESUnit: 'd', - intervalESValue: 1, - min: '2021-03-18T08:28:56.411Z', - max: '2021-07-01T07:28:56.411Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1623880800000, y: 134 }, - { x: 1623967200000, y: 152 }, - { x: 1624053600000, y: 141 }, - { x: 1624140000000, y: 138 }, - { x: 1624226400000, y: 142 }, - { x: 1624312800000, y: 157 }, - { x: 1624399200000, y: 149 }, - { x: 1624485600000, y: 146 }, - { x: 1624572000000, y: 170 }, - { x: 1624658400000, y: 137 }, - { x: 1624744800000, y: 150 }, - { x: 1624831200000, y: 144 }, - { x: 1624917600000, y: 147 }, - { x: 1625004000000, y: 137 }, - { x: 1625090400000, y: 66 }, - ], - } as unknown as UnifiedHistogramChartData; + (services.data.query.queryString.getDefaultQuery as jest.Mock).mockReturnValue({ + language: 'kuery', + query: '', + }); + (searchSourceInstanceMock.fetch$ as jest.Mock).mockImplementation( + jest.fn().mockReturnValue(of({ rawResponse: { hits: { total: noHits ? 0 : 2 } } })) + ); const props = { + dataView: dataViewWithTimefieldMock, services: unifiedHistogramServicesMock, hits: noHits ? undefined @@ -91,7 +63,6 @@ async function mountComponent({ description: 'test', scale: 2, }, - data: chartData, }, appendHistogram, onEditVisualization: onEditVisualization || undefined, From e45eef313bc44a8e0407b2e189533e6efc4d340e Mon Sep 17 00:00:00 2001 From: Dzmitry Tamashevich Date: Fri, 4 Nov 2022 18:07:26 +0300 Subject: [PATCH 3/3] [Discover] fix some jest tests --- .../main/hooks/use_saved_search.test.ts | 1 - .../hooks/use_saved_search_messages.test.ts | 5 +- .../application/main/utils/fetch_all.ts | 2 +- .../main/utils/fetch_documents.test.ts | 20 +---- .../chart/build_bucket_interval.test.ts | 31 +------ .../public/chart/build_bucket_interval.ts | 2 +- .../public/chart/histogram.test.tsx | 83 +++---------------- .../public/chart/use_chart_panels.test.ts | 4 - .../public/layout/layout.test.tsx | 18 ++-- .../translations/translations/fr-FR.json | 1 - .../translations/translations/ja-JP.json | 1 - .../translations/translations/zh-CN.json | 1 - 12 files changed, 33 insertions(+), 136 deletions(-) diff --git a/src/plugins/discover/public/application/main/hooks/use_saved_search.test.ts b/src/plugins/discover/public/application/main/hooks/use_saved_search.test.ts index 34cdeb232be88..f46378053d355 100644 --- a/src/plugins/discover/public/application/main/hooks/use_saved_search.test.ts +++ b/src/plugins/discover/public/application/main/hooks/use_saved_search.test.ts @@ -45,7 +45,6 @@ describe('test useSavedSearch', () => { expect(result.current.data$.main$.getValue().fetchStatus).toBe(FetchStatus.LOADING); expect(result.current.data$.documents$.getValue().fetchStatus).toBe(FetchStatus.LOADING); expect(result.current.data$.totalHits$.getValue().fetchStatus).toBe(FetchStatus.LOADING); - expect(result.current.data$.charts$.getValue().fetchStatus).toBe(FetchStatus.LOADING); }); test('refetch$ triggers a search', async () => { const { history, searchSessionManager } = createSearchSessionMock(); diff --git a/src/plugins/discover/public/application/main/hooks/use_saved_search_messages.test.ts b/src/plugins/discover/public/application/main/hooks/use_saved_search_messages.test.ts index 1159aee1c5d13..5b9b96db1afaf 100644 --- a/src/plugins/discover/public/application/main/hooks/use_saved_search_messages.test.ts +++ b/src/plugins/discover/public/application/main/hooks/use_saved_search_messages.test.ts @@ -62,7 +62,10 @@ describe('test useSavedSearch message generators', () => { done(); } }); - sendLoadingMsg(main$, RecordRawType.DOCUMENT); + sendLoadingMsg(main$, { + foundDocuments: true, + recordRawType: RecordRawType.DOCUMENT, + }); }); test('sendErrorMsg', (done) => { const main$ = new BehaviorSubject({ fetchStatus: FetchStatus.PARTIAL }); diff --git a/src/plugins/discover/public/application/main/utils/fetch_all.ts b/src/plugins/discover/public/application/main/utils/fetch_all.ts index 146f41c871276..82cf4712848b3 100644 --- a/src/plugins/discover/public/application/main/utils/fetch_all.ts +++ b/src/plugins/discover/public/application/main/utils/fetch_all.ts @@ -148,7 +148,7 @@ export function fetchAll( .catch(sendErrorTo(dataSubjects.documents$, dataSubjects.main$)); // Return a promise that will resolve once all the requests have finished or failed - return Promise.allSettled([documents]).then(() => { + return documents.then(() => { // Send a complete message to main$ once all queries are done and if main$ // is not already in an ERROR state, e.g. because the document query has failed. // This will only complete main$, if it hasn't already been completed previously diff --git a/src/plugins/discover/public/application/main/utils/fetch_documents.test.ts b/src/plugins/discover/public/application/main/utils/fetch_documents.test.ts index 4809da54655be..28738cdc522c9 100644 --- a/src/plugins/discover/public/application/main/utils/fetch_documents.test.ts +++ b/src/plugins/discover/public/application/main/utils/fetch_documents.test.ts @@ -8,12 +8,11 @@ import { fetchDocuments } from './fetch_documents'; import { throwError as throwErrorRx, of } from 'rxjs'; import { RequestAdapter } from '@kbn/inspector-plugin/common'; -import { savedSearchMock, savedSearchMockWithTimeField } from '../../../__mocks__/saved_search'; +import { savedSearchMock } from '../../../__mocks__/saved_search'; import { discoverServiceMock } from '../../../__mocks__/services'; import { IKibanaSearchResponse } from '@kbn/data-plugin/public'; import { SearchResponse } from '@elastic/elasticsearch/lib/api/types'; import { FetchDeps } from './fetch_all'; -import { fetchTotalHits } from './fetch_total_hits'; import type { EsHitRecord } from '../../../types'; import { buildDataTableRecord } from '../../../utils/build_data_record'; import { dataViewMock } from '../../../__mocks__/data_view'; @@ -47,21 +46,4 @@ describe('test fetchDocuments', () => { new Error('Oh noes!') ); }); - - test('fetch$ is called with execution context containing savedSearch id', async () => { - const fetch$Mock = jest.fn().mockReturnValue( - of({ - rawResponse: { hits: { hits: [] } }, - } as unknown as IKibanaSearchResponse) - ); - - savedSearchMockWithTimeField.searchSource.fetch$ = fetch$Mock; - - await fetchTotalHits(savedSearchMockWithTimeField.searchSource, getDeps()); - expect(fetch$Mock.mock.calls[0][0].executionContext).toMatchInlineSnapshot(` - Object { - "description": "fetch total hits", - } - `); - }); }); diff --git a/src/plugins/unified_histogram/public/chart/build_bucket_interval.test.ts b/src/plugins/unified_histogram/public/chart/build_bucket_interval.test.ts index 0ccd23357b347..737d77ced1c02 100644 --- a/src/plugins/unified_histogram/public/chart/build_bucket_interval.test.ts +++ b/src/plugins/unified_histogram/public/chart/build_bucket_interval.test.ts @@ -11,7 +11,7 @@ import { dataViewWithTimefieldMock } from '../__mocks__/data_view_with_timefield import { calculateBounds } from '@kbn/data-plugin/public'; import { buildBucketInterval } from './build_bucket_interval'; -describe('buildChartData', () => { +describe('buildBucketInterval', () => { const getOptions = () => { const response = { took: 0, @@ -75,35 +75,6 @@ describe('buildChartData', () => { }; }; - const expectedChartData = { - xAxisOrderedValues: [1664996400000, 1664998200000, 1665000000000, 1665001800000, 1665003600000], - xAxisFormat: { id: 'date', params: { pattern: 'HH:mm:ss.SSS' } }, - xAxisLabel: 'timestamp per 0 milliseconds', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: 'P0D', - intervalESUnit: 'ms', - intervalESValue: 0, - min: '1991-03-29T08:04:00.694Z', - max: '2021-03-29T07:04:00.695Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1664996400000, y: 6 }, - { x: 1664998200000, y: 2 }, - { x: 1665000000000, y: 3 }, - { x: 1665001800000, y: 8 }, - { x: 1665003600000, y: 10 }, - ], - }; - - it('should return the correct data', () => { - const { bucketInterval, chartData } = buildBucketInterval(getOptions()); - expect(bucketInterval!.toString()).toEqual('P0D'); - expect(JSON.stringify(chartData)).toEqual(JSON.stringify(expectedChartData)); - }); - it('should return an empty object if response or timeInterval is undefined', () => { expect( buildBucketInterval({ diff --git a/src/plugins/unified_histogram/public/chart/build_bucket_interval.ts b/src/plugins/unified_histogram/public/chart/build_bucket_interval.ts index c038b79543b4c..84e286cfc05ee 100644 --- a/src/plugins/unified_histogram/public/chart/build_bucket_interval.ts +++ b/src/plugins/unified_histogram/public/chart/build_bucket_interval.ts @@ -15,7 +15,7 @@ import { getChartAggConfigs } from './get_chart_agg_configs'; /** * Convert the response from the chart request into a format that can be used * by the unified histogram chart. The returned object should be used to update - * {@link UnifiedHistogramChartContext.bucketInterval} and {@link UnifiedHistogramChartContext.data}. + * time range interval of histogram. */ export const buildBucketInterval = ({ data, diff --git a/src/plugins/unified_histogram/public/chart/histogram.test.tsx b/src/plugins/unified_histogram/public/chart/histogram.test.tsx index 3e1213978e385..b684988c6d54c 100644 --- a/src/plugins/unified_histogram/public/chart/histogram.test.tsx +++ b/src/plugins/unified_histogram/public/chart/histogram.test.tsx @@ -6,55 +6,13 @@ * Side Public License, v 1. */ import { mountWithIntl } from '@kbn/test-jest-helpers'; -import type { UnifiedHistogramChartData, UnifiedHistogramFetchStatus } from '../types'; +import type { UnifiedHistogramFetchStatus } from '../types'; import { Histogram } from './histogram'; import React from 'react'; import { unifiedHistogramServicesMock } from '../__mocks__/services'; +import { dataViewWithTimefieldMock } from '../__mocks__/data_view_with_timefield'; -const chartData = { - xAxisOrderedValues: [ - 1623880800000, 1623967200000, 1624053600000, 1624140000000, 1624226400000, 1624312800000, - 1624399200000, 1624485600000, 1624572000000, 1624658400000, 1624744800000, 1624831200000, - 1624917600000, 1625004000000, 1625090400000, - ], - xAxisFormat: { id: 'date', params: { pattern: 'YYYY-MM-DD' } }, - xAxisLabel: 'order_date per day', - yAxisFormat: { id: 'number' }, - ordered: { - date: true, - interval: { - asMilliseconds: jest.fn(), - }, - intervalESUnit: 'd', - intervalESValue: 1, - min: '2021-03-18T08:28:56.411Z', - max: '2021-07-01T07:28:56.411Z', - }, - yAxisLabel: 'Count', - values: [ - { x: 1623880800000, y: 134 }, - { x: 1623967200000, y: 152 }, - { x: 1624053600000, y: 141 }, - { x: 1624140000000, y: 138 }, - { x: 1624226400000, y: 142 }, - { x: 1624312800000, y: 157 }, - { x: 1624399200000, y: 149 }, - { x: 1624485600000, y: 146 }, - { x: 1624572000000, y: 170 }, - { x: 1624658400000, y: 137 }, - { x: 1624744800000, y: 150 }, - { x: 1624831200000, y: 144 }, - { x: 1624917600000, y: 147 }, - { x: 1625004000000, y: 137 }, - { x: 1625090400000, y: 66 }, - ], -} as unknown as UnifiedHistogramChartData; - -function mountComponent( - status: UnifiedHistogramFetchStatus, - data: UnifiedHistogramChartData | null = chartData, - error?: Error -) { +function mountComponent(status: UnifiedHistogramFetchStatus, error?: Error) { const services = unifiedHistogramServicesMock; services.data.query.timefilter.timefilter.getAbsoluteTime = () => { return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' }; @@ -65,18 +23,20 @@ function mountComponent( const props = { services: unifiedHistogramServicesMock, chart: { - status, hidden: false, timeInterval: 'auto', - bucketInterval: { - scaled: true, - description: 'test', - scale: 2, - }, - data: data ?? undefined, - error, }, timefilterUpdateHandler, + dataView: dataViewWithTimefieldMock, + filters: [], + query: { + language: 'kuery', + query: '', + }, + timeRange: { + from: '2020-05-14T11:05:13.590', + to: '2020-05-14T11:20:13.590', + }, }; return mountWithIntl(); @@ -87,21 +47,4 @@ describe('Histogram', () => { const component = mountComponent('complete'); expect(component.find('[data-test-subj="unifiedHistogramChart"]').exists()).toBe(true); }); - - it('renders error correctly', () => { - const component = mountComponent('error', null, new Error('Loading error')); - expect(component.find('[data-test-subj="unifiedHistogramChart"]').exists()).toBe(false); - expect(component.find('[data-test-subj="unifiedHistogramErrorChartContainer"]').exists()).toBe( - true - ); - expect( - component.find('[data-test-subj="unifiedHistogramErrorChartText"]').get(1).props.children - ).toBe('Loading error'); - }); - - it('renders loading state correctly', () => { - const component = mountComponent('loading', null); - expect(component.find('[data-test-subj="unifiedHistogramChart"]').exists()).toBe(true); - expect(component.find('[data-test-subj="unifiedHistogramChartLoading"]').exists()).toBe(true); - }); }); diff --git a/src/plugins/unified_histogram/public/chart/use_chart_panels.test.ts b/src/plugins/unified_histogram/public/chart/use_chart_panels.test.ts index 71e2d3e4a705a..aec3f1a8e291f 100644 --- a/src/plugins/unified_histogram/public/chart/use_chart_panels.test.ts +++ b/src/plugins/unified_histogram/public/chart/use_chart_panels.test.ts @@ -19,7 +19,6 @@ describe('test useChartPanels', () => { closePopover: jest.fn(), onResetChartHeight: jest.fn(), chart: { - status: 'complete', hidden: true, timeInterval: 'auto', }, @@ -39,7 +38,6 @@ describe('test useChartPanels', () => { closePopover: jest.fn(), onResetChartHeight: jest.fn(), chart: { - status: 'complete', hidden: false, timeInterval: 'auto', }, @@ -59,7 +57,6 @@ describe('test useChartPanels', () => { onTimeIntervalChange: jest.fn(), closePopover: jest.fn(), chart: { - status: 'complete', hidden: false, timeInterval: 'auto', }, @@ -78,7 +75,6 @@ describe('test useChartPanels', () => { closePopover: jest.fn(), onResetChartHeight, chart: { - status: 'complete', hidden: false, timeInterval: 'auto', }, diff --git a/src/plugins/unified_histogram/public/layout/layout.test.tsx b/src/plugins/unified_histogram/public/layout/layout.test.tsx index 73b97c8f64def..0673d255362c4 100644 --- a/src/plugins/unified_histogram/public/layout/layout.test.tsx +++ b/src/plugins/unified_histogram/public/layout/layout.test.tsx @@ -6,13 +6,16 @@ * Side Public License, v 1. */ +import { searchSourceInstanceMock } from '@kbn/data-plugin/common/search/search_source/mocks'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import type { ReactWrapper } from 'enzyme'; import React from 'react'; import { act } from 'react-dom/test-utils'; +import { of } from 'rxjs'; import { Chart } from '../chart'; import { Panels, PANELS_MODE } from '../panels'; import type { UnifiedHistogramChartContext, UnifiedHistogramHitsContext } from '../types'; +import { dataViewWithTimefieldMock } from '../__mocks__/data_view_with_timefield'; import { unifiedHistogramServicesMock } from '../__mocks__/services'; import { UnifiedHistogramLayout, UnifiedHistogramLayoutProps } from './layout'; @@ -35,14 +38,8 @@ describe('Layout', () => { }); const createChart = (): UnifiedHistogramChartContext => ({ - status: 'complete', hidden: false, timeInterval: 'auto', - bucketInterval: { - scaled: true, - description: 'test', - scale: 2, - }, }); const mountComponent = async ({ @@ -59,12 +56,21 @@ describe('Layout', () => { return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' }; }; + (services.data.query.queryString.getDefaultQuery as jest.Mock).mockReturnValue({ + language: 'kuery', + query: '', + }); + (searchSourceInstanceMock.fetch$ as jest.Mock).mockImplementation( + jest.fn().mockReturnValue(of({ rawResponse: { hits: { total: 2 } } })) + ); + const component = mountWithIntl( ); diff --git a/x-pack/plugins/translations/translations/fr-FR.json b/x-pack/plugins/translations/translations/fr-FR.json index 57fc3ad319fe7..c42c82362e468 100644 --- a/x-pack/plugins/translations/translations/fr-FR.json +++ b/x-pack/plugins/translations/translations/fr-FR.json @@ -2221,7 +2221,6 @@ "discover.helpMenu.appName": "Découverte", "discover.inspectorRequestDataTitleChart": "Données du graphique", "discover.inspectorRequestDataTitleDocuments": "Documents", - "discover.inspectorRequestDescriptionChart": "Cette requête interroge Elasticsearch afin de récupérer les données d'agrégation pour le graphique.", "discover.inspectorRequestDescriptionDocument": "Cette requête interroge Elasticsearch afin de récupérer les documents.", "discover.json.codeEditorAriaLabel": "Affichage JSON en lecture seule d’un document Elasticsearch", "discover.json.copyToClipboardLabel": "Copier dans le presse-papiers", diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 3e0425fcb222b..b3ab75165960f 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -2217,7 +2217,6 @@ "discover.helpMenu.appName": "Discover", "discover.inspectorRequestDataTitleChart": "グラフデータ", "discover.inspectorRequestDataTitleDocuments": "ドキュメント", - "discover.inspectorRequestDescriptionChart": "このリクエストはElasticsearchにクエリをかけ、グラフの集計データを取得します。", "discover.inspectorRequestDescriptionDocument": "このリクエストはElasticsearchにクエリをかけ、ドキュメントを取得します。", "discover.json.codeEditorAriaLabel": "Elasticsearch ドキュメントの JSON ビューのみを読み込む", "discover.json.copyToClipboardLabel": "クリップボードにコピー", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 4ca62119353f0..1adc45ea80d44 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -2221,7 +2221,6 @@ "discover.helpMenu.appName": "Discover", "discover.inspectorRequestDataTitleChart": "图表数据", "discover.inspectorRequestDataTitleDocuments": "文档", - "discover.inspectorRequestDescriptionChart": "此请求将查询 Elasticsearch 以获取图表的聚合数据。", "discover.inspectorRequestDescriptionDocument": "此请求将查询 Elasticsearch 以获取文档。", "discover.json.codeEditorAriaLabel": "Elasticsearch 文档的只读 JSON 视图", "discover.json.copyToClipboardLabel": "复制到剪贴板",