Skip to content

Commit

Permalink
[Discover] Update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jughosta committed Nov 2, 2022
1 parent f09663a commit 3c215c5
Showing 1 changed file with 73 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { getDiscoverStateMock } from '../../../../__mocks__/discover_state.mock'
import { DiscoverAppStateProvider } from '../../services/discover_app_state_container';
import * as ExistingFieldsServiceApi from '@kbn/unified-field-list-plugin/public/services/field_existing/load_field_existing';
import { createDiscoverServicesMock } from '../../../../__mocks__/services';
import type { AggregateQuery, Query } from '@kbn/es-query';

jest.mock('@kbn/unified-field-list-plugin/public/services/field_stats', () => ({
loadFieldStats: jest.fn().mockResolvedValue({
Expand Down Expand Up @@ -65,23 +66,26 @@ jest.mock('@kbn/unified-field-list-plugin/public/services/field_stats', () => ({
}),
}));

const mockServices = {
...createDiscoverServicesMock(),
capabilities: {
visualize: {
show: true,
},
discover: {
save: false,
function createMockServices() {
const mockServices = {
...createDiscoverServicesMock(),
capabilities: {
visualize: {
show: true,
},
discover: {
save: false,
},
},
},
docLinks: { links: { discover: { fieldTypeHelp: '' } } },
dataViewEditor: {
userPermissions: {
editDataView: jest.fn(() => true),
docLinks: { links: { discover: { fieldTypeHelp: '' } } },
dataViewEditor: {
userPermissions: {
editDataView: jest.fn(() => true),
},
},
},
} as unknown as DiscoverServices;
} as unknown as DiscoverServices;
return mockServices;
}

const mockfieldCounts: Record<string, number> = {};
const mockCalcFieldCounts = jest.fn(() => {
Expand All @@ -102,24 +106,15 @@ jest.mock('../../utils/calc_field_counts', () => ({

jest.spyOn(ExistingFieldsServiceApi, 'loadFieldExisting').mockImplementation(async () => ({
indexPatternTitle: 'test',
existingFieldNames: Object.keys(mockCalcFieldCounts()),
existingFieldNames: Object.keys(mockfieldCounts),
}));
jest.spyOn(mockServices.dataViews, 'get').mockImplementation(async (dataViewId) => {
return [stubLogstashDataView].find((dw) => dw.id === dataViewId)!;
});

function getCompProps(): DiscoverSidebarResponsiveProps {
const dataView = stubLogstashDataView;
dataView.toSpec = jest.fn(() => ({}));

const hits = getDataTableRecords(dataView);

const dataViewList = [
{ id: '0', title: 'b' } as DataViewListItem,
{ id: '1', title: 'a' } as DataViewListItem,
{ id: '2', title: 'c' } as DataViewListItem,
];

for (const hit of hits) {
for (const key of Object.keys(hit.flattened)) {
mockfieldCounts[key] = (mockfieldCounts[key] || 0) + 1;
Expand All @@ -136,7 +131,7 @@ function getCompProps(): DiscoverSidebarResponsiveProps {
fetchStatus: FetchStatus.COMPLETE,
fields: [] as string[],
}) as AvailableFields$,
dataViewList,
dataViewList: [dataView as DataViewListItem],
onChangeDataView: jest.fn(),
onAddFilter: jest.fn(),
onAddField: jest.fn(),
Expand All @@ -150,30 +145,52 @@ function getCompProps(): DiscoverSidebarResponsiveProps {
};
}

function getAppStateContainer({ query }: { query?: Query | AggregateQuery }) {
const appStateContainer = getDiscoverStateMock({ isTimeBased: true }).appStateContainer;
appStateContainer.set({
query: query ?? { query: '', language: 'lucene' },
filters: [],
});
return appStateContainer;
}

async function mountComponent(
props: DiscoverSidebarResponsiveProps,
appStateParams: { query?: Query | AggregateQuery } = {},
services?: DiscoverServices
): Promise<ReactWrapper<DiscoverSidebarResponsiveProps>> {
let comp: ReactWrapper<DiscoverSidebarResponsiveProps>;
const mockedServices = services ?? createMockServices();
mockedServices.data.dataViews.getIdsWithTitle = jest.fn(async () => props.dataViewList);
mockedServices.data.dataViews.get = jest.fn().mockImplementation(async (id) => {
return [props.selectedDataView].find((d) => d!.id === id);
});

await act(async () => {
comp = await mountWithIntl(
<KibanaContextProvider services={mockedServices}>
<DiscoverAppStateProvider value={getAppStateContainer(appStateParams)}>
<DiscoverSidebarResponsive {...props} />
</DiscoverAppStateProvider>
</KibanaContextProvider>
);
// wait for lazy modules
await new Promise((resolve) => setTimeout(resolve, 0));
await comp.update();
});

await comp!.update();

return comp!;
}

describe('discover responsive sidebar', function () {
let props: DiscoverSidebarResponsiveProps;
let comp: ReactWrapper<DiscoverSidebarResponsiveProps>;

beforeAll(async () => {
props = getCompProps();
await act(async () => {
const appStateContainer = getDiscoverStateMock({ isTimeBased: true }).appStateContainer;
appStateContainer.set({
query: { query: '', language: 'lucene' },
filters: [],
});

comp = await mountWithIntl(
<KibanaContextProvider services={mockServices}>
<DiscoverAppStateProvider value={appStateContainer}>
<DiscoverSidebarResponsive {...props} />
</DiscoverAppStateProvider>
</KibanaContextProvider>
);
// wait for lazy modules
await new Promise((resolve) => setTimeout(resolve, 0));
await comp.update();
});
comp = await mountComponent(props);
});

it('should have Selected Fields, Available Fields, and Popular Fields sections', async function () {
Expand All @@ -185,7 +202,7 @@ describe('discover responsive sidebar', function () {

expect(selectedFieldsCount.text()).toBe('1');
expect(popularFieldsCount.text()).toBe('1');
expect(availableFieldsCount.text()).toBe('3'); // TODO: double check
expect(availableFieldsCount.text()).toBe('3');
expect(emptyFieldsCount.text()).toBe('20');
expect(metaFieldsCount.text()).toBe('2');
expect(mockCalcFieldCounts.mock.calls.length).toBe(1);
Expand Down Expand Up @@ -235,12 +252,14 @@ describe('discover responsive sidebar', function () {
expect(mockCalcFieldCounts.mock.calls.length).toBe(1);
});

it('should show "Add a field" button to create a runtime field', () => {
expect(mockServices.dataViewEditor.userPermissions.editDataView).toHaveBeenCalled();
it('should show "Add a field" button to create a runtime field', async () => {
const services = createMockServices();
comp = await mountComponent(props, {}, services);
expect(services.dataViewEditor.userPermissions.editDataView).toHaveBeenCalled();
expect(findTestSubject(comp, 'dataView-add-field_btn').length).toBe(1);
});

it('should not show "Add a field" button on the sql mode', () => {
it('should not show "Add a field" button on the sql mode', async () => {
const initialProps = getCompProps();
const propsWithTextBasedMode = {
...initialProps,
Expand All @@ -251,46 +270,17 @@ describe('discover responsive sidebar', function () {
result: getDataTableRecords(stubLogstashDataView),
}) as DataDocuments$,
};
const appStateContainer = getDiscoverStateMock({ isTimeBased: true }).appStateContainer;
appStateContainer.set({
const compInViewerMode = await mountComponent(propsWithTextBasedMode, {
query: { sql: 'SELECT * FROM `index`' },
});
const compInViewerMode = mountWithIntl(
<KibanaContextProvider services={mockServices}>
<DiscoverAppStateProvider value={appStateContainer}>
<DiscoverSidebarResponsive {...propsWithTextBasedMode} />
</DiscoverAppStateProvider>
</KibanaContextProvider>
);
expect(findTestSubject(compInViewerMode, 'indexPattern-add-field_btn').length).toBe(0);
});

it('should not show "Add a field" button in viewer mode', () => {
const mockedServicesInViewerMode = {
...mockServices,
dataViewEditor: {
...mockServices.dataViewEditor,
userPermissions: {
...mockServices.dataViewEditor.userPermissions,
editDataView: jest.fn(() => false),
},
},
};
const appStateContainer = getDiscoverStateMock({ isTimeBased: true }).appStateContainer;
appStateContainer.set({
query: { query: '', language: 'lucene' },
filters: [],
});
const compInViewerMode = mountWithIntl(
<KibanaContextProvider services={mockedServicesInViewerMode}>
<DiscoverAppStateProvider value={appStateContainer}>
<DiscoverSidebarResponsive {...props} />
</DiscoverAppStateProvider>
</KibanaContextProvider>
);
expect(
mockedServicesInViewerMode.dataViewEditor.userPermissions.editDataView
).toHaveBeenCalled();
it('should not show "Add a field" button in viewer mode', async () => {
const services = createMockServices();
services.dataViewEditor.userPermissions.editDataView = jest.fn(() => false);
const compInViewerMode = await mountComponent(props, {}, services);
expect(services.dataViewEditor.userPermissions.editDataView).toHaveBeenCalled();
expect(findTestSubject(compInViewerMode, 'dataView-add-field_btn').length).toBe(0);
});
});

0 comments on commit 3c215c5

Please sign in to comment.