kibana/x-pack/plugins/lens/public/mocks/services_mock.tsx
Maja Grubic 069550d72a
[KibanaReact] Use settings service in useUiSetting hook (#154710)
## Summary

Fixes: https://github.com/elastic/kibana/issues/149347

This PR replaces deprecated `uiSettings` client with `settings.client`
in `useUiSetting` hook. As a result, all consumers of the hook need to
provide `settings` service to Kibana context. The majority of this PR is
providing the `settings` as a dependency to affected plugins. It would
be great if sometime in the future we could get rid of `uiSettings`
entirely.

`CodeEditor` is one of the components relying on this hook, which caused
a lot of the changes in this PR.

If you have been tagged for review it means your code is using
`useUiSetting` hook directly, or is consuming `CodeEditor` component. I
have been focused on updating plugins that had failing functional tests,
but would appreciate a manual pass on this as well.

xoxo


### Checklist

Delete any items that are not applicable to this PR.

~ [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)~
~- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials~
- [X] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
~- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard
accessibility](https://webaim.org/techniques/keyboard/))~
~- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))~
~- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)~
~- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))~
~- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)~


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Maja Grubic <maja.grubic@elastic.co>
Co-authored-by: Patryk Kopyciński <contact@patrykkopycinski.com>
2023-05-12 10:47:56 +03:00

188 lines
6.7 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React from 'react';
import { Subject } from 'rxjs';
import { coreMock } from '@kbn/core/public/mocks';
import { navigationPluginMock } from '@kbn/navigation-plugin/public/mocks';
import { UI_SETTINGS } from '@kbn/data-plugin/public';
import { indexPatternFieldEditorPluginMock } from '@kbn/data-view-field-editor-plugin/public/mocks';
import { indexPatternEditorPluginMock } from '@kbn/data-view-editor-plugin/public/mocks';
import { inspectorPluginMock } from '@kbn/inspector-plugin/public/mocks';
import { spacesPluginMock } from '@kbn/spaces-plugin/public/mocks';
import { dashboardPluginMock } from '@kbn/dashboard-plugin/public/mocks';
import { dataViewPluginMocks } from '@kbn/data-views-plugin/public/mocks';
import { chartPluginMock } from '@kbn/charts-plugin/public/mocks';
import { DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public';
import { unifiedSearchPluginMock } from '@kbn/unified-search-plugin/public/mocks';
import {
mockAttributeService,
createEmbeddableStateTransferMock,
} from '@kbn/embeddable-plugin/public/mocks';
import { fieldFormatsServiceMock } from '@kbn/field-formats-plugin/public/mocks';
import type { EmbeddableStateTransfer } from '@kbn/embeddable-plugin/public';
import { presentationUtilPluginMock } from '@kbn/presentation-util-plugin/public/mocks';
import { uiActionsPluginMock } from '@kbn/ui-actions-plugin/public/mocks';
import { settingsServiceMock } from '@kbn/core-ui-settings-browser-mocks';
import type { LensAttributeService } from '../lens_attribute_service';
import type {
LensByValueInput,
LensByReferenceInput,
LensSavedObjectAttributes,
LensUnwrapMetaInfo,
} from '../embeddable/embeddable';
import { DOC_TYPE } from '../../common/constants';
import { LensAppServices } from '../app_plugin/types';
import { mockDataPlugin } from './data_plugin_mock';
import { getLensInspectorService } from '../lens_inspector_service';
import { SavedObjectIndexStore } from '../persistence';
const startMock = coreMock.createStart();
export const defaultDoc = {
savedObjectId: '1234',
title: 'An extremely cool default document!',
expression: 'definitely a valid expression',
visualizationType: 'testVis',
state: {
query: 'kuery',
filters: [{ query: { match_phrase: { src: 'test' } }, meta: { index: 'index-pattern-0' } }],
datasourceStates: {
testDatasource: 'datasource',
},
visualization: {},
},
references: [{ type: 'index-pattern', id: '1', name: 'index-pattern-0' }],
} as unknown as Document;
export const exactMatchDoc = {
attributes: {
...defaultDoc,
},
sharingSavedObjectProps: {
outcome: 'exactMatch',
},
};
export function makeDefaultServices(
sessionIdSubject = new Subject<string>(),
sessionId: string | undefined = undefined,
doc = defaultDoc
): jest.Mocked<LensAppServices> {
const core = coreMock.createStart({ basePath: '/testbasepath' });
core.uiSettings.get.mockImplementation(
jest.fn((type) => {
if (type === UI_SETTINGS.TIMEPICKER_TIME_DEFAULTS) {
return { from: 'now-7d', to: 'now' };
} else if (type === UI_SETTINGS.SEARCH_QUERY_LANGUAGE) {
return 'kuery';
} else if (type === 'state:storeInSessionStorage') {
return false;
} else {
return [];
}
})
);
const dataViewsMock = dataViewPluginMocks.createStartContract();
dataViewsMock.get.mockImplementation(
jest.fn((id) =>
Promise.resolve({
id,
isTimeBased: () => true,
fields: [],
isPersisted: () => true,
toSpec: () => ({}),
})
) as unknown as DataViewsPublicPluginStart['get']
);
dataViewsMock.getIdsWithTitle.mockImplementation(jest.fn(async () => []));
const navigationStartMock = navigationPluginMock.createStartContract();
jest
.spyOn(navigationStartMock.ui.AggregateQueryTopNavMenu.prototype, 'constructor')
.mockImplementation(() => {
return <div className="topNavMenu" />;
});
function makeAttributeService(): LensAttributeService {
const attributeServiceMock = mockAttributeService<
LensSavedObjectAttributes,
LensByValueInput,
LensByReferenceInput,
LensUnwrapMetaInfo
>(
DOC_TYPE,
{
saveMethod: jest.fn(),
unwrapMethod: jest.fn(),
checkForDuplicateTitle: jest.fn(),
},
core
);
attributeServiceMock.unwrapAttributes = jest.fn().mockResolvedValue(exactMatchDoc);
attributeServiceMock.wrapAttributes = jest.fn().mockResolvedValue({
savedObjectId: (doc as unknown as LensByReferenceInput).savedObjectId,
});
return attributeServiceMock;
}
return {
http: core.http,
chrome: core.chrome,
overlays: core.overlays,
uiSettings: core.uiSettings,
settings: settingsServiceMock.createStartContract(),
executionContext: core.executionContext,
navigation: navigationStartMock,
notifications: core.notifications,
attributeService: makeAttributeService(),
inspector: {
adapters: getLensInspectorService(inspectorPluginMock.createStartContract()).adapters,
inspect: jest.fn(),
close: jest.fn(),
},
dashboard: dashboardPluginMock.createStartContract(),
presentationUtil: presentationUtilPluginMock.createStartContract(core),
dashboardFeatureFlag: { allowByValueEmbeddables: false },
savedObjectStore: {
load: jest.fn(),
search: jest.fn(),
save: jest.fn(),
} as unknown as SavedObjectIndexStore,
stateTransfer: createEmbeddableStateTransferMock() as EmbeddableStateTransfer,
getOriginatingAppName: jest.fn(() => 'defaultOriginatingApp'),
application: {
...core.application,
capabilities: {
...core.application.capabilities,
visualize: { save: true, saveQuery: true, show: true, createShortUrl: true },
},
getUrlForApp: jest.fn((appId: string) => `/testbasepath/app/${appId}#/`),
},
data: mockDataPlugin(sessionIdSubject, sessionId),
dataViews: dataViewsMock,
fieldFormats: fieldFormatsServiceMock.createStartContract(),
storage: {
get: jest.fn(),
set: jest.fn(),
remove: jest.fn(),
clear: jest.fn(),
},
uiActions: uiActionsPluginMock.createStartContract(),
spaces: spacesPluginMock.createStartContract(),
charts: chartPluginMock.createSetupContract(),
dataViewFieldEditor: indexPatternFieldEditorPluginMock.createStartContract(),
dataViewEditor: indexPatternEditorPluginMock.createStartContract(),
unifiedSearch: unifiedSearchPluginMock.createStartContract(),
docLinks: startMock.docLinks,
};
}