Skip to content

Commit

Permalink
Fix Jest tests
Browse files Browse the repository at this point in the history
  • Loading branch information
davismcphee committed May 13, 2024
1 parent e4d4031 commit a936f16
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { LocalStorageMock } from '../../../../__mocks__/local_storage_mock';
import { DiscoverServices } from '../../../../build_services';
import { discoverServiceMock } from '../../../../__mocks__/services';
import { DiscoverTourProvider } from '../../../../components/discover_tour';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';
import { DiscoverMainProvider } from '../../state_management/discover_state_provider';

const defaultServices = {
...discoverServiceMock,
Expand Down Expand Up @@ -62,9 +64,11 @@ describe('Document Explorer Update callout', () => {
it('should start a tour when the button is clicked', () => {
const result = mountWithIntl(
<KibanaContextProvider services={defaultServices}>
<DiscoverTourProvider>
<DocumentExplorerUpdateCallout />
</DiscoverTourProvider>
<DiscoverMainProvider value={getDiscoverStateMock({})}>
<DiscoverTourProvider>
<DocumentExplorerUpdateCallout />
</DiscoverTourProvider>
</DiscoverMainProvider>
</KibanaContextProvider>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,49 @@ import React from 'react';
import { mountWithIntl } from '@kbn/test-jest-helpers';
import type { DatatableColumn } from '@kbn/expressions-plugin/common';
import { SelectedVSAvailableCallout } from './selected_vs_available_callout';
import { DiscoverMainProvider } from '../../state_management/discover_state_provider';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';

describe('SelectedVSAvailableCallout', () => {
it('should render the callout if in ES|QL mode and the selected columns are less than the available ones', async () => {
const stateContainer = getDiscoverStateMock({});
stateContainer.appState.update({ query: { esql: 'select *' } });
const component = mountWithIntl(
<SelectedVSAvailableCallout
esqlQueryColumns={
[
{ id: '1', name: 'extension', meta: { type: 'text' } },
{ id: '2', name: 'bytes', meta: { type: 'number' } },
{ id: '3', name: '@timestamp', meta: { type: 'date' } },
] as DatatableColumn[]
}
selectedColumns={['bytes']}
/>
<DiscoverMainProvider value={stateContainer}>
<SelectedVSAvailableCallout
esqlQueryColumns={
[
{ id: '1', name: 'extension', meta: { type: 'text' } },
{ id: '2', name: 'bytes', meta: { type: 'number' } },
{ id: '3', name: '@timestamp', meta: { type: 'date' } },
] as DatatableColumn[]
}
selectedColumns={['bytes']}
/>
</DiscoverMainProvider>
);
expect(component.find('[data-test-subj="dscSelectedColumnsCallout"]').exists()).toBe(true);
});

it('should not render the callout if not in ES|QL mode', async () => {
const component = mountWithIntl(
<SelectedVSAvailableCallout esqlQueryColumns={undefined} selectedColumns={['bytes']} />
<DiscoverMainProvider value={getDiscoverStateMock({})}>
<SelectedVSAvailableCallout esqlQueryColumns={undefined} selectedColumns={['bytes']} />
</DiscoverMainProvider>
);
expect(component.find('[data-test-subj="dscSelectedColumnsCallout"]').exists()).toBe(false);
});

it('should not render the callout if in ES|QL mode but the selected columns are equal with the available ones', async () => {
const component = mountWithIntl(
<SelectedVSAvailableCallout
esqlQueryColumns={
[{ id: '2', name: 'bytes', meta: { type: 'number' } }] as DatatableColumn[]
}
selectedColumns={['bytes']}
/>
<DiscoverMainProvider value={getDiscoverStateMock({})}>
<SelectedVSAvailableCallout
esqlQueryColumns={
[{ id: '2', name: 'bytes', meta: { type: 'number' } }] as DatatableColumn[]
}
selectedColumns={['bytes']}
/>
</DiscoverMainProvider>
);
expect(component.find('[data-test-subj="dscSelectedColumnsCallout"]').exists()).toBe(false);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,8 @@ describe('useDiscoverHistogram', () => {
});

it('should return the isChartLoading params for ES|QL mode', async () => {
const stateContainer = getStateContainer();
stateContainer.appState.update({ query: { esql: 'from *' } });
const { hook } = await renderUseDiscoverHistogram();
const isChartLoading = hook.result.current.isChartLoading;
expect(isChartLoading).toBe(false);
Expand Down Expand Up @@ -386,6 +388,7 @@ describe('useDiscoverHistogram', () => {
searchSessionId: string;
}>();
const stateContainer = getStateContainer();
stateContainer.appState.update({ query: { esql: 'from *' } });
stateContainer.dataState.fetch$ = fetch$;
const { hook } = await renderUseDiscoverHistogram({ stateContainer });
act(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,19 @@
*/

import { BehaviorSubject } from 'rxjs';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, WrapperComponent } from '@testing-library/react-hooks';
import { buildDataTableRecord } from '@kbn/discover-utils';
import { dataViewMock, esHitsMockWithSort } from '@kbn/discover-utils/src/__mocks__';
import { useFetchMoreRecords } from './use_fetch_more_records';
import { useFetchMoreRecords, UseFetchMoreRecordsParams } from './use_fetch_more_records';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';
import {
DataDocuments$,
DataTotalHits$,
} from '../../state_management/discover_data_state_container';
import { FetchStatus } from '../../../types';
import { DiscoverMainProvider } from '../../state_management/discover_state_provider';
import React from 'react';
import { DiscoverStateContainer } from '../../state_management/discover_state';

describe('useFetchMoreRecords', () => {
const records = esHitsMockWithSort.map((hit) => buildDataTableRecord(hit, dataViewMock));
Expand All @@ -43,17 +46,27 @@ describe('useFetchMoreRecords', () => {
return stateContainer;
};

const getWrapper = (
stateContainer: DiscoverStateContainer
): WrapperComponent<UseFetchMoreRecordsParams> => {
return ({ children }) => (
<DiscoverMainProvider value={stateContainer}>
<>{children}</>
</DiscoverMainProvider>
);
};

it('should not be allowed if all records are already loaded', async () => {
const stateContainer = getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 3,
});
const {
result: { current },
} = renderHook((props) => useFetchMoreRecords(props), {
initialProps: {
stateContainer: getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 3,
}),
},
wrapper: getWrapper(stateContainer),
initialProps: { stateContainer },
});

expect(current.onFetchMoreRecords).toBeUndefined();
Expand All @@ -62,67 +75,68 @@ describe('useFetchMoreRecords', () => {
});

it('should be allowed when there are more records to load', async () => {
const stateContainer = getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
});
const {
result: { current },
} = renderHook((props) => useFetchMoreRecords(props), {
initialProps: {
stateContainer: getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
}),
},
wrapper: getWrapper(stateContainer),
initialProps: { stateContainer },
});
expect(current.onFetchMoreRecords).toBeDefined();
expect(current.isMoreDataLoading).toBe(false);
expect(current.totalHits).toBe(5);
});

it('should not be allowed when there is no initial documents', async () => {
const stateContainer = getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 0,
totalRecordsCount: 5,
});
const {
result: { current },
} = renderHook((props) => useFetchMoreRecords(props), {
initialProps: {
stateContainer: getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 0,
totalRecordsCount: 5,
}),
},
wrapper: getWrapper(stateContainer),
initialProps: { stateContainer },
});
expect(current.onFetchMoreRecords).toBeUndefined();
expect(current.isMoreDataLoading).toBe(false);
expect(current.totalHits).toBe(5);
});

it('should return loading status correctly', async () => {
const stateContainer = getStateContainer({
fetchStatus: FetchStatus.LOADING_MORE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
});
const {
result: { current },
} = renderHook((props) => useFetchMoreRecords(props), {
initialProps: {
stateContainer: getStateContainer({
fetchStatus: FetchStatus.LOADING_MORE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
}),
},
wrapper: getWrapper(stateContainer),
initialProps: { stateContainer },
});
expect(current.onFetchMoreRecords).toBeDefined();
expect(current.isMoreDataLoading).toBe(true);
expect(current.totalHits).toBe(5);
});

it('should not be allowed for ES|QL queries', async () => {
const stateContainer = getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
});
stateContainer.appState.update({ query: { esql: 'from *' } });
const {
result: { current },
} = renderHook((props) => useFetchMoreRecords(props), {
initialProps: {
stateContainer: getStateContainer({
fetchStatus: FetchStatus.COMPLETE,
loadedRecordsCount: 3,
totalRecordsCount: 5,
}),
},
wrapper: getWrapper(stateContainer),
initialProps: { stateContainer },
});
expect(current.onFetchMoreRecords).toBeUndefined();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { type Filter } from '@kbn/es-query';
import { DiscoverNoResults, DiscoverNoResultsProps } from './no_results';
import { createDiscoverServicesMock } from '../../../../__mocks__/services';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';
import { DiscoverMainProvider } from '../../state_management/discover_state_provider';

jest.spyOn(RxApi, 'lastValueFrom').mockImplementation(async () => ({
rawResponse: {
Expand Down Expand Up @@ -61,25 +62,28 @@ async function mountAndFindSubjects(
>
) {
const isTimeBased = props.dataView.isTimeBased();
const stateContainer = getDiscoverStateMock({ isTimeBased });

let component: ReactWrapper;

await act(async () => {
component = await mountWithIntl(
act(() => {
component = mountWithIntl(
<KibanaContextProvider services={services}>
<DiscoverNoResults
stateContainer={getDiscoverStateMock({ isTimeBased })}
isTimeBased={isTimeBased}
onDisableFilters={() => {}}
{...props}
/>
<DiscoverMainProvider value={stateContainer}>
<DiscoverNoResults
stateContainer={stateContainer}
isTimeBased={isTimeBased}
onDisableFilters={() => {}}
{...props}
/>
</DiscoverMainProvider>
</KibanaContextProvider>
);
});

await new Promise((resolve) => setTimeout(resolve, 0));
await act(async () => {
await component!.update();
act(() => {
component!.update();
});

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export function fetchAll(

// Mark all subjects as loading
sendLoadingMsg(dataSubjects.main$);
sendLoadingMsg(dataSubjects.documents$);
sendLoadingMsg(dataSubjects.documents$, { query });

// histogram for data view mode will send `loading` for totalHits$
if (isEsqlQuery) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Side Public License, v 1.
*/

import { isOfAggregateQueryType, isOfQueryType } from '@kbn/es-query';
import { isOfAggregateQueryType } from '@kbn/es-query';
import type { IUiSettingsClient } from '@kbn/core-ui-settings-browser';
import { DiscoverAppState, AppStateUrl } from '../discover_app_state_container';
import { migrateLegacyQuery } from '../../../../utils/migrate_legacy_query';
Expand All @@ -21,8 +21,11 @@ export function cleanupUrlState(
appStateFromUrl: AppStateUrl,
uiSettings: IUiSettingsClient
): DiscoverAppState {
if (isOfQueryType(appStateFromUrl.query) && !appStateFromUrl.query.language) {
appStateFromUrl.query = migrateLegacyQuery(appStateFromUrl.query);
const query = appStateFromUrl.query;
const isEsqlQuery = isOfAggregateQueryType(query);

if (!isEsqlQuery && query && !query.language) {
appStateFromUrl.query = migrateLegacyQuery(query);
}

if (typeof appStateFromUrl.sort?.[0] === 'string') {
Expand All @@ -48,8 +51,6 @@ export function cleanupUrlState(
delete appStateFromUrl.rowsPerPage;
}

const isEsqlQuery = isOfAggregateQueryType(appStateFromUrl.query);

if (
appStateFromUrl.sampleSize &&
(isEsqlQuery || // not supported yet for ES|QL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,16 @@ import { discoverServiceMock } from '../../__mocks__/services';
import { DiscoverTourProvider } from './discover_tour_provider';
import { useDiscoverTourContext } from './discover_tour_context';
import { DISCOVER_TOUR_STEP_ANCHORS } from './discover_tour_anchors';
import { DiscoverMainProvider } from '../../application/main/state_management/discover_state_provider';
import { getDiscoverStateMock } from '../../__mocks__/discover_state.mock';

describe('Discover tour', () => {
const mountComponent = (innerContent: JSX.Element) => {
return mountWithIntl(
<KibanaContextProvider services={discoverServiceMock}>
<DiscoverTourProvider>{innerContent}</DiscoverTourProvider>
<DiscoverMainProvider value={getDiscoverStateMock({})}>
<DiscoverTourProvider>{innerContent}</DiscoverTourProvider>
</DiscoverMainProvider>
</KibanaContextProvider>
);
};
Expand Down

0 comments on commit a936f16

Please sign in to comment.