"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.resetReactDomCreatePortalMock = exports.createAppRootMockRenderer = void 0; var _react = _interopRequireDefault(require("react")); var _history = require("history"); var _react2 = require("@testing-library/react"); var _reactQuery = require("@tanstack/react-query"); var _mocks = require("@kbn/core/public/mocks"); var _common = require("@kbn/fleet-plugin/common"); var _reactHooks = require("@testing-library/react-hooks"); var _reactDom = _interopRequireDefault(require("react-dom")); var _experimental_features_service = require("../../experimental_features_service"); var _intersection_observer_mock = require("../intersection_observer_mock"); var _dependencies_start_mock = require("./dependencies_start_mock"); var _test_utils = require("../../store/test_utils"); var _test_providers = require("../test_providers"); var _store = require("../../store"); var _app_root_provider = require("./app_root_provider"); var _middleware = require("../../../management/store/middleware"); var _kibana_react = require("../../lib/kibana/kibana_react.mock"); var _ = require(".."); var _constants = require("../../../../common/constants"); var _kibana = require("../../lib/kibana"); var _app_links = require("../../links/app_links"); var _mocks2 = require("../../../management/mocks"); var _experimental_features = require("../../../../common/experimental_features"); /* * 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. */ const REAL_REACT_DOM_CREATE_PORTAL = _reactDom.default.createPortal; /** * Resets the mock that is applied to `createPortal()` by default. * **IMPORTANT** : Make sure you call this function from a `before*()` or `after*()` callback * * @example * * // Turn off for test using Enzyme * beforeAll(() => resetReactDomCreatePortalMock()); */ const resetReactDomCreatePortalMock = () => { _reactDom.default.createPortal = REAL_REACT_DOM_CREATE_PORTAL; }; exports.resetReactDomCreatePortalMock = resetReactDomCreatePortalMock; beforeAll(() => { // Mocks the React DOM module to ensure compatibility with react-testing-library and avoid // error like: // ``` // TypeError: parentInstance.children.indexOf is not a function // at appendChild (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7183:39) // ``` // @see https://github.com/facebook/react/issues/11565 _reactDom.default.createPortal = jest.fn((...args) => { REAL_REACT_DOM_CREATE_PORTAL(...args); // Needed for react-Test-library. See: // https://github.com/facebook/react/issues/11565 return args[0]; }); }); afterAll(() => { resetReactDomCreatePortalMock(); }); // Defined a private custom reducer that reacts to an action that enables us to update the // store with new values for technical preview features/flags. Because the `action.type` is a `Symbol`, // and its not exported the action can only be `dispatch`'d from this module const UpdateExperimentalFeaturesTestActionType = Symbol('updateExperimentalFeaturesTestAction'); const experimentalFeaturesReducer = (state = _.mockGlobalState.app, action) => { if (action.type === UpdateExperimentalFeaturesTestActionType) { return { ...state, enableExperimental: { ...state.enableExperimental, ...action.payload } }; } return state; }; /** * Creates a mocked endpoint app context custom renderer that can be used to render * component that depend upon the application's surrounding context providers. * Factory also returns the content that was used to create the custom renderer, allowing * for further customization. */ const createAppRootMockRenderer = () => { const history = (0, _history.createMemoryHistory)(); const coreStart = createCoreStartMock(history); const depsStart = (0, _dependencies_start_mock.depsStartMock)(); const middlewareSpy = (0, _test_utils.createSpyMiddleware)(); const { storage } = (0, _.createSecuritySolutionStorageMock)(); const startServices = (0, _kibana_react.createStartServicesMock)(coreStart); const storeReducer = { ..._.SUB_PLUGINS_REDUCER, // This is ok here because the store created by this testing utility (see below) does // not pull in the non-sub-plugin reducers app: experimentalFeaturesReducer }; const store = (0, _store.createStore)(_.mockGlobalState, storeReducer, _test_providers.kibanaObservable, storage, // @ts-expect-error ts upgrade v4.7.4 [...(0, _middleware.managementMiddlewareFactory)(coreStart, depsStart), middlewareSpy.actionSpyMiddleware]); const queryClient = new _reactQuery.QueryClient({ defaultOptions: { queries: { // turns retries off retry: false, // prevent jest did not exit errors cacheTime: Infinity } }, // hide react-query output in console logger: { error: () => {}, // eslint-disable-next-line no-console log: console.log, // eslint-disable-next-line no-console warn: console.warn } }); const AppWrapper = ({ children }) => /*#__PURE__*/_react.default.createElement(_app_root_provider.AppRootProvider, { store: store, history: history, coreStart: coreStart, depsStart: depsStart, startServices: startServices, queryClient: queryClient }, children); const render = (ui, options) => { (0, _intersection_observer_mock.applyIntersectionObserverMock)(); return (0, _react2.render)(ui, { wrapper: AppWrapper, ...options }); }; const renderHook = (hookFn, options = {}) => { return (0, _reactHooks.renderHook)(hookFn, { wrapper: AppWrapper, ...options }); }; const renderReactQueryHook = async (hookFn, waitForHook = 'isSuccess', options = {}) => { const { result: hookResult, waitFor } = renderHook(hookFn, options); if (waitForHook) { await waitFor(() => { return hookResult.current[waitForHook]; }); } return hookResult.current; }; _experimental_features_service.ExperimentalFeaturesService.init({ experimentalFeatures: _experimental_features.allowedExperimentalValues }); const setExperimentalFlag = flags => { _experimental_features_service.ExperimentalFeaturesService.init({ experimentalFeatures: { ..._experimental_features.allowedExperimentalValues, ...flags } }); store.dispatch({ type: UpdateExperimentalFeaturesTestActionType, payload: flags }); }; // Initialize the singleton `KibanaServices` with global services created for this test instance. // The module (`../../lib/kibana`) could have been mocked at the test level via `jest.mock()`, // and if so, then we set the return value of `KibanaServices.get` instead of calling `KibanaServices.init()` const globalKibanaServicesParams = { ...startServices, kibanaVersion: '8.0.0', kibanaBranch: 'main' }; if (jest.isMockFunction(_kibana.KibanaServices.get)) { _kibana.KibanaServices.get.mockReturnValue(globalKibanaServicesParams); } else { _kibana.KibanaServices.init(globalKibanaServicesParams); } // Some APIs need to be mocked right from the start because they are called as soon as the store is initialized applyDefaultCoreHttpMocks(coreStart.http); return { store, history, coreStart, depsStart, startServices, middlewareSpy, AppWrapper, render, renderHook, renderReactQueryHook, setExperimentalFlag, queryClient }; }; exports.createAppRootMockRenderer = createAppRootMockRenderer; const createCoreStartMock = history => { const coreStart = _mocks.coreMock.createStart({ basePath: '/mock' }); const linkPaths = getLinksPaths(_app_links.links); // Mock the certain APP Ids returned by `application.getUrlForApp()` coreStart.application.getUrlForApp.mockImplementation((appId, { deepLinkId, path } = {}) => { switch (appId) { case _common.PLUGIN_ID: return '/app/fleet'; case _constants.APP_UI_ID: return `${_constants.APP_PATH}${deepLinkId && linkPaths[deepLinkId] ? linkPaths[deepLinkId] : ''}${path !== null && path !== void 0 ? path : ''}`; default: return `${appId} not mocked!`; } }); coreStart.application.navigateToApp.mockImplementation((appId, { deepLinkId, path } = {}) => { if (appId === _constants.APP_UI_ID) { history.push(`${deepLinkId && linkPaths[deepLinkId] ? linkPaths[deepLinkId] : ''}${path !== null && path !== void 0 ? path : ''}`); } return Promise.resolve(); }); coreStart.application.navigateToUrl.mockImplementation(url => { history.push(url.replace(_constants.APP_PATH, '')); return Promise.resolve(); }); return coreStart; }; const getLinksPaths = appLinks => { return appLinks.reduce((result, link) => { if (link.path) { result[link.id] = link.path; } if (link.links) { return { ...result, ...getLinksPaths(link.links) }; } return result; }, {}); }; const applyDefaultCoreHttpMocks = http => { // Need to mock getting the endpoint package from the fleet API because it is used as soon // as the store middleware for Endpoint list is initialized, thus mocking it here would avoid // unnecessary errors being output to the console (0, _mocks2.fleetGetPackageHttpMock)(http, { ignoreUnMockedApiRouteErrors: true }); };