Skip to content

Commit

Permalink
Fixing more unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kertal committed Oct 25, 2022
1 parent 9e4d706 commit 567a752
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 86 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
*/

import React from 'react';
import { shallowWithIntl } from '@kbn/test-jest-helpers';
import { mountWithIntl } from '@kbn/test-jest-helpers';
import { DiscoverTopNav, DiscoverTopNavProps } from './discover_topnav';
import { TopNavMenuData } from '@kbn/navigation-plugin/public';
import { TopNavMenu, TopNavMenuData } from '@kbn/navigation-plugin/public';
import { Query } from '@kbn/es-query';
import { setHeaderActionMenuMounter } from '../../../../kibana_services';
import { discoverServiceMock } from '../../../../__mocks__/services';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';
import { DiscoverMainProvider } from '../../services/discover_state_react';
import { dataViewMock } from '../../../../__mocks__/data_view';

setHeaderActionMenuMounter(jest.fn());

Expand All @@ -27,9 +28,11 @@ jest.mock('@kbn/kibana-react-plugin/public', () => ({

function getProps(savePermissions = true): DiscoverTopNavProps {
discoverServiceMock.capabilities.discover!.save = savePermissions;
const stateContainer = getDiscoverStateMock({ isTimeBased: true });
stateContainer.internalState.transitions.setDataView(dataViewMock);

return {
stateContainer: getDiscoverStateMock({ isTimeBased: true }),
stateContainer,
navigateTo: jest.fn(),
query: {} as Query,
savedQuery: '',
Expand All @@ -45,24 +48,25 @@ function getProps(savePermissions = true): DiscoverTopNavProps {
describe('Discover topnav component', () => {
test('generated config of TopNavMenu config is correct when discover save permissions are assigned', () => {
const props = getProps(true);
const component = shallowWithIntl(<DiscoverTopNav {...props} />, {
context: {
wrappingComponent: DiscoverMainProvider,
wrappingComponentProps: { value: getDiscoverStateMock({}) },
},
});
const topMenuConfig = component.props().config.map((obj: TopNavMenuData) => obj.id);
const component = mountWithIntl(
<DiscoverMainProvider value={props.stateContainer}>
<DiscoverTopNav {...props} />
</DiscoverMainProvider>
);
const topNavMenu = component.find(TopNavMenu);
const topMenuConfig = topNavMenu.props().config?.map((obj: TopNavMenuData) => obj.id);
expect(topMenuConfig).toEqual(['options', 'new', 'open', 'share', 'inspect', 'save']);
});

test('generated config of TopNavMenu config is correct when no discover save permissions are assigned', () => {
const props = getProps(false);
const component = shallowWithIntl(
<DiscoverMainProvider value={getDiscoverStateMock({})}>
const component = mountWithIntl(
<DiscoverMainProvider value={props.stateContainer}>
<DiscoverTopNav {...props} />
</DiscoverMainProvider>
);
const topMenuConfig = component.props().config.map((obj: TopNavMenuData) => obj.id);
const topNavMenu = component.find(TopNavMenu).props();
const topMenuConfig = topNavMenu.config?.map((obj: TopNavMenuData) => obj.id);
expect(topMenuConfig).toEqual(['options', 'new', 'open', 'share', 'inspect']);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ export const DiscoverTopNav = ({
textBasedLanguageModeErrors ? [textBasedLanguageModeErrors] : undefined
}
onTextBasedSavedAndExit={onTextBasedSavedAndExit}
data-test-subj="dsc_topNav"
/>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { DiscoverServices } from '../../../../build_services';
import { i18nServiceMock } from '@kbn/core/public/mocks';
import { ReactElement } from 'react';
import { discoverServiceMock } from '../../../../__mocks__/services';
import * as persistSavedSearchUtils from '../../utils/persist_saved_search';
import { SavedSearch } from '@kbn/saved-search-plugin/public';
import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock';

Expand Down Expand Up @@ -70,6 +69,7 @@ describe('onSaveSearch', () => {
const serviceMock = discoverServiceMock;
const stateMock = getDiscoverStateMock({ isTimeBased: true });
stateMock.setAppState({ rowsPerPage: 250 });
stateMock.internalState.transitions.setDataView(dataViewMock);
let saveModal: ReactElement | undefined;
jest.spyOn(savedObjectsPlugin, 'showSaveModal').mockImplementationOnce((modal) => {
saveModal = modal;
Expand All @@ -78,6 +78,7 @@ describe('onSaveSearch', () => {
...savedSearchMock,
tags: ['tag1', 'tag2'],
};

await onSaveSearch({
dataView: dataViewMock,
navigateTo: jest.fn(),
Expand All @@ -86,13 +87,12 @@ describe('onSaveSearch', () => {
stateContainer: stateMock,
updateAdHocDataViewId: jest.fn(),
});

expect(savedSearch.tags).toEqual(['tag1', 'tag2']);
jest
.spyOn(persistSavedSearchUtils, 'persistSavedSearch')
.mockImplementationOnce((newSavedSearch, _) => {
savedSearch = newSavedSearch;
return Promise.resolve(newSavedSearch.id);
});
stateMock.savedSearchState.persist = jest.fn((newSavedSearch: SavedSearch) => {
savedSearch = newSavedSearch;
return Promise.resolve({ id: newSavedSearch.id });
});
saveModal?.props.onSave({
newTitle: savedSearch.title,
newCopyOnSave: false,
Expand Down Expand Up @@ -128,12 +128,10 @@ describe('onSaveSearch', () => {
updateAdHocDataViewId: jest.fn(),
});
expect(savedSearch.tags).toEqual(['tag1', 'tag2']);
jest
.spyOn(persistSavedSearchUtils, 'persistSavedSearch')
.mockImplementationOnce((newSavedSearch, _) => {
savedSearch = newSavedSearch;
return Promise.resolve(newSavedSearch.id);
});
stateMock.savedSearchState.persist = jest.fn((newSavedSearch: SavedSearch) => {
savedSearch = newSavedSearch;
return Promise.resolve({ id: newSavedSearch.id });
});
saveModal?.props.onSave({
newTitle: savedSearch.title,
newCopyOnSave: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* Side Public License, v 1.
*/

import { createSearchSourceMock } from '@kbn/data-plugin/public/mocks';
import type { DataView } from '@kbn/data-views-plugin/public';
import { act, renderHook } from '@testing-library/react-hooks';
import {
Expand Down Expand Up @@ -67,12 +68,20 @@ const mockDataView = {
toSpec: () => ({}),
} as DataView;

const savedSearchMock = {
id: 'some-id',
searchSource: createSearchSourceMock({ index: mockDataView }),
};

describe('useAdHocDataViews', () => {
it('should save data view with new id and update saved search', async () => {
const stateContainer = getDiscoverStateMock({ isTimeBased: true });
stateContainer.savedSearchState.set(savedSearchMock);

const hook = renderHook((d: DataView) =>
useAdHocDataViews({
dataView: mockDataView,
stateContainer: getDiscoverStateMock({ isTimeBased: true }),
stateContainer,
services: discoverServiceMock,
})
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,30 @@ import { useDiscoverState } from './use_discover_state';
import { setUrlTracker } from '../../../kibana_services';
import { urlTrackerMock } from '../../../__mocks__/url_tracker.mock';
import { getDiscoverStateMock } from '../../../__mocks__/discover_state.mock';
import React, { ReactElement } from 'react';
import { DiscoverMainProvider } from '../services/discover_state_react';
import { dataViewMock } from '../../../__mocks__/data_view';
setUrlTracker(urlTrackerMock);

describe('test useDiscoverState', () => {
test('return is valid', async () => {
const stateContainer = getDiscoverStateMock({ isTimeBased: true });
stateContainer.internalState.transitions.setDataView(dataViewMock);

const { result } = renderHook(() => {
return useDiscoverState({
services: discoverServiceMock,
setExpandedDoc: jest.fn(),
stateContainer,
});
});
const { result } = renderHook(
() => {
return useDiscoverState({
services: discoverServiceMock,
setExpandedDoc: jest.fn(),
stateContainer,
});
},
{
wrapper: ({ children }: { children: ReactElement }) => (
<DiscoverMainProvider value={stateContainer}>{children}</DiscoverMainProvider>
),
}
);
expect(result.current.adHocDataViewList).toBeInstanceOf(Object);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ function getInitialState(
services,
});
return handleSourceColumnState(
savedSearch.id
savedSearch.id && (!appStateFromUrl || !Object.keys(appStateFromUrl).length)
? { ...defaultAppState }
: {
...defaultAppState,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,21 @@
*/
import { Subject } from 'rxjs';
import { waitFor } from '@testing-library/react';
import { createSearchSessionMock } from '../../../__mocks__/search_session';
import { discoverServiceMock } from '../../../__mocks__/services';
import { savedSearchMock, savedSearchMockWithSQL } from '../../../__mocks__/saved_search';
import { savedSearchMockWithSQL } from '../../../__mocks__/saved_search';
import { getDiscoverStateContainer } from './discover_state';
import { FetchStatus } from '../../types';
import { setUrlTracker } from '../../../kibana_services';
import { urlTrackerMock } from '../../../__mocks__/url_tracker.mock';
import { getDataStateContainer, RecordRawType } from './discover_data_state_container';
import { RecordRawType } from './discover_data_state_container';
import { createBrowserHistory } from 'history';
import { getDiscoverStateMock } from '../../../__mocks__/discover_state.mock';

setUrlTracker(urlTrackerMock);
describe('test getDataStateContainer', () => {
test('return is valid', async () => {
const { history, searchSessionManager } = createSearchSessionMock();
const stateContainer = getDiscoverStateContainer({
savedSearch: savedSearchMock,
services: discoverServiceMock,
history,
});

const dataState = getDataStateContainer({
getSavedSearch: () => savedSearchMock,
searchSessionManager,
services: discoverServiceMock,
getAppState: () => stateContainer.appState.getState(),
});
const stateContainer = getDiscoverStateMock({ isTimeBased: true });
const dataState = stateContainer.dataState;

expect(dataState.refetch$).toBeInstanceOf(Subject);
expect(dataState.data$.main$.getValue().fetchStatus).toBe(FetchStatus.LOADING);
Expand All @@ -40,23 +30,13 @@ describe('test getDataStateContainer', () => {
expect(dataState.data$.charts$.getValue().fetchStatus).toBe(FetchStatus.LOADING);
});
test('refetch$ triggers a search', async () => {
const { history, searchSessionManager } = createSearchSessionMock();
const stateContainer = getDiscoverStateContainer({
savedSearch: savedSearchMock,
services: discoverServiceMock,
history,
});
const stateContainer = getDiscoverStateMock({ isTimeBased: true });

discoverServiceMock.data.query.timefilter.timefilter.getTime = jest.fn(() => {
return { from: '2021-05-01T20:00:00Z', to: '2021-05-02T20:00:00Z' };
});
const dataState = stateContainer.dataState;

const dataState = getDataStateContainer({
getSavedSearch: () => savedSearchMock,
searchSessionManager,
services: discoverServiceMock,
getAppState: () => stateContainer.appState.getState(),
});
const unsubscribe = dataState.subscribe();

dataState.refetch$.next(undefined);
Expand All @@ -70,40 +50,34 @@ describe('test getDataStateContainer', () => {
});

test('reset sets back to initial state', async () => {
const { history, searchSessionManager } = createSearchSessionMock();
const stateContainer = getDiscoverStateContainer({
savedSearch: savedSearchMock,
services: discoverServiceMock,
history,
});
const stateContainer = getDiscoverStateMock({ isTimeBased: true });

discoverServiceMock.data.query.timefilter.timefilter.getTime = jest.fn(() => {
return { from: '2021-05-01T20:00:00Z', to: '2021-05-02T20:00:00Z' };
});

const dataState = getDataStateContainer({
getSavedSearch: () => savedSearchMock,
searchSessionManager,
services: discoverServiceMock,
getAppState: () => stateContainer.appState.getState(),
});
const dataState = stateContainer.dataState;
const unsubscribe = dataState.subscribe();

await waitFor(() => {
expect(dataState.data$.main$.value.fetchStatus).toBe(FetchStatus.LOADING);
});

dataState.refetch$.next(undefined);

await waitFor(() => {
expect(dataState.data$.main$.value.fetchStatus).toBe(FetchStatus.COMPLETE);
});
dataState.refetch$.next('reset');

dataState.reset();
await waitFor(() => {
expect(dataState.data$.main$.getValue().fetchStatus).toBe(FetchStatus.LOADING);
expect(dataState.data$.main$.value.fetchStatus).toBe(FetchStatus.LOADING);
});

unsubscribe();
});

test('useSavedSearch returns plain record raw type', async () => {
const { history } = createSearchSessionMock();
const history = createBrowserHistory();
const stateContainer = getDiscoverStateContainer({
savedSearch: savedSearchMockWithSQL,
services: discoverServiceMock,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('Test discover initial state sort handling', () => {
services: discoverServiceMock,
history,
});
await state.setAppState({}, true);
// await state.setAppState({}, true);
const stopSync = state.appState.syncState().stop;
expect(state.appState.getState().sort).toEqual([['order_date', 'desc']]);
stopSync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const mockFetchTotalHits = fetchTotalHits as unknown as jest.MockedFunction<type
const mockFetchChart = fetchChart as unknown as jest.MockedFunction<typeof fetchChart>;
const mockFetchSQL = fetchSql as unknown as jest.MockedFunction<typeof fetchSql>;

function subjectCollector<T>(subject: Subject<T>): () => Promise<T[]> {
export function subjectCollector<T>(subject: Subject<T>): () => Promise<T[]> {
const promise = firstValueFrom(
subject.pipe(reduce((history, value) => history.concat([value]), [] as T[]))
);
Expand Down Expand Up @@ -230,7 +230,9 @@ describe('test fetchAll', () => {
];
const documents = hits.map((hit) => buildDataTableRecord(hit, dataViewMock));
mockFetchSQL.mockResolvedValue(documents);

const query = { sql: 'SELECT * from foo' };
savedSearchMock.searchSource.setField('query', query);
deps = {
abortController: new AbortController(),
data: discoverServiceMock.data,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { useColumns } from './use_data_grid_columns';
import { dataViewMock } from '../__mocks__/data_view';
import { configMock } from '../__mocks__/config';
import { dataViewsMock } from '../__mocks__/data_views';
import { AppState } from '../application/context/services/context_state';
import { Capabilities } from '@kbn/core/types';

describe('useColumns', () => {
Expand All @@ -21,9 +20,7 @@ describe('useColumns', () => {
dataView: dataViewMock,
dataViews: dataViewsMock,
setAppState: () => {},
state: {
columns: ['Time', 'message'],
} as AppState,
columns: ['Time', 'message'],
useNewFieldsApi: false,
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,6 @@ class SearchBarUI<QT extends (Query | AggregateQuery) | Query = Query> extends C
};

public onQueryBarChange = (queryAndDateRange: { dateRange: TimeRange; query?: QT | Query }) => {
console.log('{ onQueryBarChange }', this.props.onQueryChange);
this.setState({
query: queryAndDateRange.query,
dateRangeFrom: queryAndDateRange.dateRange.from,
Expand Down

0 comments on commit 567a752

Please sign in to comment.