Skip to content

Commit d7d985b

Browse files
Convert 'kbn-unified-histogram' tests
1 parent 835d565 commit d7d985b

1 file changed

Lines changed: 105 additions & 51 deletions

File tree

src/platform/packages/shared/kbn-unified-histogram/components/chart/histogram.test.tsx

Lines changed: 105 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -7,49 +7,63 @@
77
* License v3.0 only", or the "Server Side Public License, v 1".
88
*/
99

10-
import { mountWithIntl } from '@kbn/test-jest-helpers';
1110
import type { HistogramProps } from './histogram';
12-
import { Histogram } from './histogram';
11+
import type { UnifiedHistogramFetch$ } from '../../types';
1312
import React from 'react';
13+
import { act, screen } from '@testing-library/react';
14+
import { allSuggestionsMock } from '../../__mocks__/suggestions';
1415
import { BehaviorSubject } from 'rxjs';
15-
import { unifiedHistogramServicesMock } from '../../__mocks__/services';
16-
import { getLensVisMock } from '../../__mocks__/lens_vis';
17-
import { dataViewWithTimefieldMock } from '../../__mocks__/data_view_with_timefield';
1816
import { createDefaultInspectorAdapters } from '@kbn/expressions-plugin/common';
19-
import type { UnifiedHistogramFetch$ } from '../../types';
20-
import { act } from 'react-dom/test-utils';
21-
import { RequestStatus } from '@kbn/inspector-plugin/public';
22-
import { getLensProps, useLensProps } from './hooks/use_lens_props';
17+
import { dataViewWithTimefieldMock } from '../../__mocks__/data_view_with_timefield';
2318
import { getFetch$Mock, getFetchParamsMock } from '../../__mocks__/fetch_params';
19+
import { getLensProps, useLensProps } from './hooks/use_lens_props';
20+
import { getLensVisMock } from '../../__mocks__/lens_vis';
21+
import { Histogram } from './histogram';
22+
import { renderWithI18n } from '@kbn/test-jest-helpers';
23+
import { RequestStatus } from '@kbn/inspector-plugin/public';
24+
import { unifiedHistogramServicesMock } from '../../__mocks__/services';
25+
26+
type CombinedProps = Omit<HistogramProps, 'requestData' | 'lensProps'> &
27+
Parameters<typeof useLensProps>[0];
2428

2529
const getMockLensAttributes = async () => {
2630
const query = {
2731
language: 'kuery',
2832
query: '',
2933
};
34+
3035
return (
3136
await getLensVisMock({
32-
filters: [],
33-
query,
37+
breakdownField: dataViewWithTimefieldMock.getFieldByName('extension'),
3438
columns: [],
35-
isPlainRecord: false,
3639
dataView: dataViewWithTimefieldMock,
40+
filters: [],
41+
isPlainRecord: false,
42+
query,
3743
timeInterval: 'auto',
38-
breakdownField: dataViewWithTimefieldMock.getFieldByName('extension'),
3944
})
4045
).visContext;
4146
};
4247

43-
type CombinedProps = Omit<HistogramProps, 'requestData' | 'lensProps'> &
44-
Parameters<typeof useLensProps>[0];
48+
const getEmbeddableProps = () => {
49+
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent as jest.Mock;
50+
expect(embeddable).toHaveBeenCalled();
51+
52+
return embeddable.mock.calls[embeddable.mock.calls.length - 1][0];
53+
};
4554

46-
async function mountComponent(isPlainRecord = false, hasLensSuggestions = false) {
55+
const renderComponent = async ({
56+
isPlainRecord = false,
57+
hasLensSuggestions = false,
58+
}: { isPlainRecord?: boolean; hasLensSuggestions?: boolean } = {}) => {
4759
const services = unifiedHistogramServicesMock;
60+
4861
services.data.query.timefilter.timefilter.getAbsoluteTime = () => {
4962
return { from: '2020-05-14T11:05:13.590', to: '2020-05-14T11:20:13.590' };
5063
};
5164

5265
const fetch$: UnifiedHistogramFetch$ = getFetch$Mock();
66+
5367
const fetchParams = getFetchParamsMock({
5468
searchSessionId: '123',
5569
dataView: dataViewWithTimefieldMock,
@@ -61,15 +75,18 @@ async function mountComponent(isPlainRecord = false, hasLensSuggestions = false)
6175
from: '2020-05-14T11:05:13.590',
6276
to: '2020-05-14T11:20:13.590',
6377
},
78+
query: isPlainRecord ? { esql: 'FROM index1' } : undefined,
6479
});
80+
6581
const lensVisMock = await getLensVisMock({
82+
allSuggestions: hasLensSuggestions ? allSuggestionsMock : undefined,
83+
breakdownField: dataViewWithTimefieldMock.getFieldByName('extension'),
84+
columns: [],
6685
dataView: fetchParams.dataView,
67-
isPlainRecord: fetchParams.isESQLQuery,
68-
timeInterval: fetchParams.timeInterval,
6986
filters: fetchParams.filters,
87+
isPlainRecord: fetchParams.isESQLQuery,
7088
query: fetchParams.query,
71-
columns: [],
72-
breakdownField: dataViewWithTimefieldMock.getFieldByName('extension'),
89+
timeInterval: fetchParams.timeInterval,
7390
});
7491

7592
const props: CombinedProps = {
@@ -87,60 +104,77 @@ async function mountComponent(isPlainRecord = false, hasLensSuggestions = false)
87104
bucketInterval: undefined,
88105
visContext: lensVisMock.visContext!,
89106
};
107+
90108
const Wrapper = (wrapperProps: CombinedProps) => {
91109
const lensPropsContext = useLensProps(wrapperProps);
110+
92111
return lensPropsContext ? <Histogram {...wrapperProps} {...lensPropsContext} /> : null;
93112
};
94113

95-
const component = mountWithIntl(<Wrapper {...props} />);
114+
renderWithI18n(<Wrapper {...props} />);
96115

97116
act(() => {
98117
fetch$?.next({ fetchParams, lensVisServiceState: lensVisMock.lensService.state$.getValue() });
99118
});
100119

101-
return { props, fetch$, fetchParams, component: component.update(), lensVisMock };
102-
}
120+
return { fetch$, fetchParams, lensVisMock, props };
121+
};
103122

104123
describe('Histogram', () => {
124+
beforeEach(() => {
125+
(unifiedHistogramServicesMock.lens.EmbeddableComponent as jest.Mock)
126+
.mockClear()
127+
.mockImplementation(() => <div>Lens embeddable</div>);
128+
});
129+
105130
it('renders correctly', async () => {
106-
const { component } = await mountComponent();
107-
expect(component.find('[data-test-subj="unifiedHistogramChart"]').exists()).toBe(true);
131+
await renderComponent();
132+
133+
expect(screen.getByText('Lens embeddable')).toBeVisible();
108134
});
109135

110136
it('should only update lens.EmbeddableComponent props when fetch$ is triggered', async () => {
111-
const { component, fetch$, fetchParams, lensVisMock } = await mountComponent();
112-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
113-
expect(component.find(embeddable).exists()).toBe(true);
114-
let lensProps = component.find(embeddable).props();
137+
const { fetch$, fetchParams, lensVisMock } = await renderComponent();
138+
139+
expect(unifiedHistogramServicesMock.lens.EmbeddableComponent).toHaveBeenCalled();
140+
141+
let lensProps = getEmbeddableProps();
142+
115143
const originalProps = getLensProps({
116-
searchSessionId: fetchParams.searchSessionId,
117-
timeRange: fetchParams.timeRange,
118-
esqlVariables: fetchParams.esqlVariables,
119144
attributes: (await getMockLensAttributes())!.attributes,
120-
onLoad: lensProps.onLoad!,
145+
esqlVariables: fetchParams.esqlVariables,
121146
lastReloadRequestTime: fetchParams.lastReloadRequestTime,
147+
onLoad: lensProps.onLoad!,
148+
searchSessionId: fetchParams.searchSessionId,
149+
timeRange: fetchParams.timeRange,
122150
});
151+
123152
expect(lensProps).toMatchObject(expect.objectContaining(originalProps));
153+
124154
const updatedFetchParams = { ...fetchParams, searchSessionId: '321' };
125-
await act(async () => {
155+
156+
act(() => {
126157
fetch$.next({
127158
fetchParams: updatedFetchParams,
128159
lensVisServiceState: lensVisMock.lensService.state$.getValue(),
129160
});
130161
});
131-
component.update();
132-
lensProps = component.find(embeddable).props();
162+
163+
lensProps = getEmbeddableProps();
164+
133165
expect(lensProps).toMatchObject(
134166
expect.objectContaining({ ...originalProps, searchSessionId: '321' })
135167
);
136168
});
137169

138170
it('should execute onLoad correctly', async () => {
139-
const { component, props } = await mountComponent();
140-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
141-
const onLoad = component.find(embeddable).props().onLoad!;
171+
const { props } = await renderComponent();
172+
173+
const onLoad = getEmbeddableProps().onLoad!;
142174
const adapters = createDefaultInspectorAdapters();
175+
143176
adapters.tables.tables.unifiedHistogram = { meta: { statistics: { totalCount: 100 } } } as any;
177+
144178
const rawResponse = {
145179
took: 0,
146180
timed_out: false,
@@ -187,36 +221,47 @@ describe('Histogram', () => {
187221
},
188222
},
189223
};
224+
190225
jest
191226
.spyOn(adapters.requests, 'getRequests')
192227
.mockReturnValue([{ response: { json: { rawResponse } } } as any]);
228+
193229
const dataLoading$ = new BehaviorSubject<boolean | undefined>(false);
230+
194231
onLoad(true, undefined, dataLoading$);
232+
195233
expect(props.onLoad).toHaveBeenLastCalledWith(true, undefined, dataLoading$);
234+
196235
act(() => {
197236
onLoad?.(false, adapters, dataLoading$);
198237
});
238+
199239
expect(props.onLoad).toHaveBeenLastCalledWith(false, adapters, dataLoading$);
200240
});
201241

202242
it('should execute onLoad correctly when the request has a failure status', async () => {
203-
const { component, props } = await mountComponent();
204-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
205-
const onLoad = component.find(embeddable).props().onLoad!;
243+
const { props } = await renderComponent();
244+
245+
const onLoad = getEmbeddableProps().onLoad!;
206246
const adapters = createDefaultInspectorAdapters();
247+
207248
jest
208249
.spyOn(adapters.requests, 'getRequests')
209250
.mockReturnValue([{ status: RequestStatus.ERROR } as any]);
251+
210252
onLoad?.(false, adapters);
253+
211254
expect(props.onLoad).toHaveBeenLastCalledWith(false, adapters);
212255
});
213256

214257
it('should execute onLoad correctly when the response has shard failures', async () => {
215-
const { component, props } = await mountComponent();
216-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
217-
const onLoad = component.find(embeddable).props().onLoad!;
258+
const { props } = await renderComponent();
259+
260+
const onLoad = getEmbeddableProps().onLoad!;
218261
const adapters = createDefaultInspectorAdapters();
262+
219263
adapters.tables.tables.unifiedHistogram = { meta: { statistics: { totalCount: 100 } } } as any;
264+
220265
const rawResponse = {
221266
_shards: {
222267
total: 1,
@@ -231,20 +276,24 @@ describe('Histogram', () => {
231276
hits: [],
232277
},
233278
};
279+
234280
jest
235281
.spyOn(adapters.requests, 'getRequests')
236282
.mockReturnValue([{ response: { json: { rawResponse } } } as any]);
283+
237284
act(() => {
238285
onLoad?.(false, adapters);
239286
});
287+
240288
expect(props.onLoad).toHaveBeenLastCalledWith(false, adapters);
241289
});
242290

243291
it('should execute onLoad correctly for textbased language and no Lens suggestions', async () => {
244-
const { component, props } = await mountComponent(true, false);
245-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
246-
const onLoad = component.find(embeddable).props().onLoad!;
292+
const { props } = await renderComponent({ isPlainRecord: true, hasLensSuggestions: false });
293+
294+
const onLoad = getEmbeddableProps().onLoad!;
247295
const adapters = createDefaultInspectorAdapters();
296+
248297
adapters.tables.tables.layerId = {
249298
meta: { type: 'es_ql' },
250299
columns: [
@@ -266,17 +315,20 @@ describe('Histogram', () => {
266315
},
267316
],
268317
} as any;
318+
269319
act(() => {
270320
onLoad?.(false, adapters);
271321
});
322+
272323
expect(props.onLoad).toHaveBeenLastCalledWith(false, adapters);
273324
});
274325

275326
it('should execute onLoad correctly for textbased language and Lens suggestions', async () => {
276-
const { component, props } = await mountComponent(true, true);
277-
const embeddable = unifiedHistogramServicesMock.lens.EmbeddableComponent;
278-
const onLoad = component.find(embeddable).props().onLoad!;
327+
const { props } = await renderComponent({ isPlainRecord: true, hasLensSuggestions: true });
328+
329+
const onLoad = getEmbeddableProps().onLoad!;
279330
const adapters = createDefaultInspectorAdapters();
331+
280332
adapters.tables.tables.layerId = {
281333
meta: { type: 'es_ql' },
282334
columns: [
@@ -298,9 +350,11 @@ describe('Histogram', () => {
298350
},
299351
],
300352
} as any;
353+
301354
act(() => {
302355
onLoad?.(false, adapters);
303356
});
357+
304358
expect(props.onLoad).toHaveBeenLastCalledWith(false, adapters);
305359
});
306360
});

0 commit comments

Comments
 (0)