Skip to content

Commit

Permalink
[ML] Fix jest tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Mar 5, 2020
1 parent 7246934 commit 5a07ca7
Show file tree
Hide file tree
Showing 20 changed files with 113 additions and 114 deletions.
27 changes: 27 additions & 0 deletions x-pack/plugins/transform/public/app/app_dependencies.mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { coreMock } from 'src/core/public/mocks';

import { getAppProviders, AppDependencies } from './app_dependencies';

const coreSetup = coreMock.createSetup();
const coreStart = coreMock.createStart();

const appDependencies: AppDependencies = {
chrome: coreStart.chrome,
data: {},
docLinks: coreStart.docLinks,
i18n: coreStart.i18n,
notifications: coreStart.notifications,
uiSettings: coreStart.uiSettings,
savedObjects: coreStart.savedObjects,
overlays: coreStart.overlays,
http: coreSetup.http,
};

export const Providers = getAppProviders(appDependencies);
28 changes: 17 additions & 11 deletions x-pack/plugins/transform/public/app/app_dependencies.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,38 @@
import React, { createContext, useContext, ReactNode } from 'react';
import { HashRouter } from 'react-router-dom';

import { CoreSetup, CoreStart } from '../../../../../src/core/public';

import { API_BASE_PATH } from '../../common/constants';

import { PluginsDependencies } from '../plugin';
import { setDependencyCache } from '../shared_imports';

import { AuthorizationProvider } from './lib/authorization';

export interface AppDependencies {
core: any;
plugins: PluginsDependencies;
chrome: CoreStart['chrome'];
data: any;
docLinks: CoreStart['docLinks'];
http: CoreSetup['http'];
i18n: CoreStart['i18n'];
notifications: CoreStart['notifications'];
uiSettings: CoreStart['uiSettings'];
savedObjects: CoreStart['savedObjects'];
overlays: CoreStart['overlays'];
}

let DependenciesContext: React.Context<AppDependencies>;

const setAppDependencies = (deps: AppDependencies) => {
const legacyBasePath = {
prepend: deps.core.http.basePath.prepend,
get: deps.core.http.basePath.get,
prepend: deps.http.basePath.prepend,
get: deps.http.basePath.get,
remove: () => {},
};

setDependencyCache({
autocomplete: deps.plugins.data.autocomplete,
docLinks: deps.core.docLinks,
autocomplete: deps.data.autocomplete,
docLinks: deps.docLinks,
basePath: legacyBasePath as any,
});
DependenciesContext = createContext<AppDependencies>(deps);
Expand All @@ -47,15 +55,13 @@ export const useAppDependencies = () => {

export const useToastNotifications = () => {
const {
core: {
notifications: { toasts: toastNotifications },
},
notifications: { toasts: toastNotifications },
} = useAppDependencies();
return toastNotifications;
};

export const getAppProviders = (deps: AppDependencies) => {
const I18nContext = deps.core.i18n.Context;
const I18nContext = deps.i18n.Context;

// Create App dependencies context and get its provider
const AppDependenciesProvider = setAppDependencies(deps);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import React from 'react';
import { render } from '@testing-library/react';

import { getAppProviders } from '../app_dependencies';
import { Providers } from '../app_dependencies.mock';

import { ToastNotificationText } from './toast_notification_text';

Expand All @@ -16,7 +16,6 @@ jest.mock('ui/new_platform');

describe('ToastNotificationText', () => {
test('should render the text as plain text', () => {
const Providers = getAppProviders({});
const props = {
text: 'a short text message',
};
Expand All @@ -29,7 +28,6 @@ describe('ToastNotificationText', () => {
});

test('should render the text within a modal', () => {
const Providers = getAppProviders({});
const props = {
text:
'a text message that is longer than 140 characters. a text message that is longer than 140 characters. a text message that is longer than 140 characters. ',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ import { useAppDependencies } from '../app_dependencies';
const MAX_SIMPLE_MESSAGE_LENGTH = 140;

export const ToastNotificationText: FC<{ text: any }> = ({ text }) => {
const {
core: { overlays },
} = useAppDependencies();
const { overlays } = useAppDependencies();

if (typeof text === 'string' && text.length <= MAX_SIMPLE_MESSAGE_LENGTH) {
return text;
Expand Down
4 changes: 1 addition & 3 deletions x-pack/plugins/transform/public/app/hooks/use_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import { PreviewRequestBody } from '../common';
import { EsIndex } from './use_api_types';

export const useApi = () => {
const {
core: { http },
} = useAppDependencies();
const { http } = useAppDependencies();

const basePath = http.basePath.prepend('/api/transform');
const indicesBasePath = http.basePath.prepend('/api');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { TRANSFORM_DOC_PATHS } from '../constants';

export const useDocumentationLinks = () => {
const deps = useAppDependencies();
const { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } = deps.core.docLinks;
const { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } = deps.docLinks;
return {
esDocBasePath: `${ELASTIC_WEBSITE_URL}guide/en/elasticsearch/reference/${DOC_LINK_VERSION}/`,
esIndicesCreateIndex: `${ELASTIC_WEBSITE_URL}guide/en/elasticsearch/reference/${DOC_LINK_VERSION}/indices-create-index.html#indices-create-index`,
Expand Down
4 changes: 1 addition & 3 deletions x-pack/plugins/transform/public/app/hooks/use_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import { UseRequestConfig, useRequest as _useRequest } from '../../shared_import
import { useAppDependencies } from '../app_dependencies';

export const useRequest = (config: UseRequestConfig) => {
const {
core: { http },
} = useAppDependencies();
const { http } = useAppDependencies();
return _useRequest(http, config);
};
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ export const useSearchItems = (defaultSavedObjectId: string | undefined) => {
const [savedObjectId, setSavedObjectId] = useState(defaultSavedObjectId);

const appDeps = useAppDependencies();
const indexPatterns = appDeps.plugins.data.indexPatterns;
const uiSettings = appDeps.core.uiSettings;
const savedObjectsClient = appDeps.core.savedObjects.client;
const indexPatterns = appDeps.data.indexPatterns;
const uiSettings = appDeps.uiSettings;
const savedObjectsClient = appDeps.savedObjects.client;
const savedSearches = createSavedSearchesLoader({
savedObjectsClient,
indexPatterns,
chrome: appDeps.core.chrome,
overlays: appDeps.core.overlays,
chrome: appDeps.chrome,
overlays: appDeps.overlays,
});

const [searchItems, setSearchItems] = useState<SearchItems | undefined>(undefined);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
*/

import React from 'react';
import { render } from '@testing-library/react';
import { render, wait } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { getAppProviders } from '../../../../app_dependencies';
import { Providers } from '../../../../app_dependencies.mock';
import { getPivotQuery } from '../../../../common';
import { SearchItems } from '../../../../hooks/use_search_items';

Expand All @@ -18,7 +18,8 @@ jest.mock('ui/new_platform');
jest.mock('../../../../../shared_imports');

describe('Transform: <SourceIndexPreview />', () => {
test('Minimal initialization', () => {
// Using the async/await wait()/done() pattern to avoid act() errors.
test('Minimal initialization', async done => {
// Arrange
const props = {
indexPattern: {
Expand All @@ -27,7 +28,6 @@ describe('Transform: <SourceIndexPreview />', () => {
} as SearchItems['indexPattern'],
query: getPivotQuery('the-query'),
};
const Providers = getAppProviders({});
const { getByText } = render(
<Providers>
<SourceIndexPreview {...props} />
Expand All @@ -37,5 +37,7 @@ describe('Transform: <SourceIndexPreview />', () => {
// Act
// Assert
expect(getByText(`Source index ${props.indexPattern.title}`)).toBeInTheDocument();
await wait();
done();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { FC } from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import { renderHook } from '@testing-library/react-hooks';
import '@testing-library/jest-dom/extend-expect';

import { SimpleQuery } from '../../../../common';
import {
Expand All @@ -17,50 +16,31 @@ import {

jest.mock('../../../../hooks/use_api');

type Callback = () => void;
interface TestHookProps {
callback: Callback;
}

const TestHook: FC<TestHookProps> = ({ callback }) => {
callback();
return null;
};

const testHook = (callback: Callback) => {
const container = document.createElement('div');
document.body.appendChild(container);
act(() => {
ReactDOM.render(<TestHook callback={callback} />, container);
});
};

const query: SimpleQuery = {
query_string: {
query: '*',
default_operator: 'AND',
},
};

let sourceIndexObj: UseSourceIndexDataReturnType;

describe('useSourceIndexData', () => {
test('indexPattern set triggers loading', () => {
testHook(() => {
act(() => {
sourceIndexObj = useSourceIndexData(
{ id: 'the-id', title: 'the-title', fields: [] },
query,
{ pageIndex: 0, pageSize: 10 }
);
});
});
test('indexPattern set triggers loading', async done => {
const { result, waitForNextUpdate } = renderHook(() =>
useSourceIndexData({ id: 'the-id', title: 'the-title', fields: [] }, query, {
pageIndex: 0,
pageSize: 10,
})
);
const sourceIndexObj: UseSourceIndexDataReturnType = result.current;

await waitForNextUpdate();

expect(sourceIndexObj.errorMessage).toBe('');
expect(sourceIndexObj.status).toBe(SOURCE_INDEX_STATUS.LOADING);
expect(sourceIndexObj.tableItems).toEqual([]);
done();
});

// TODO add more tests to check data retrieved via `api.esSearch()`.
// This needs more investigation in regards to jest/enzyme's React Hooks support.
// This needs more investigation in regards to jest's React Hooks support.
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { getAppProviders } from '../../../../app_dependencies';
import { Providers } from '../../../../app_dependencies.mock';

import { StepCreateForm } from './step_create_form';

Expand All @@ -26,7 +26,6 @@ describe('Transform: <StepCreateForm />', () => {
onChange() {},
};

const Providers = getAppProviders({});
const { getByText } = render(
<Providers>
<StepCreateForm {...props} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ export const StepCreateForm: FC<Props> = React.memo(
);

const deps = useAppDependencies();
const indexPatterns = deps.plugins.data.indexPatterns;
const uiSettings = deps.core.uiSettings;
const indexPatterns = deps.data.indexPatterns;
const uiSettings = deps.uiSettings;
const toastNotifications = useToastNotifications();

useEffect(() => {
Expand Down Expand Up @@ -464,7 +464,7 @@ export const StepCreateForm: FC<Props> = React.memo(
defaultMessage: 'Use Discover to explore the transform.',
}
)}
href={getDiscoverUrl(indexPatternId, deps.core.http.basePath.get())}
href={getDiscoverUrl(indexPatternId, deps.http.basePath.get())}
data-test-subj="transformWizardCardDiscover"
/>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
*/

import React from 'react';
import { render } from '@testing-library/react';
import { render, wait } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { getAppProviders } from '../../../../app_dependencies';
import { Providers } from '../../../../app_dependencies.mock';
import {
getPivotQuery,
PivotAggsConfig,
Expand All @@ -24,7 +24,8 @@ jest.mock('ui/new_platform');
jest.mock('../../../../../shared_imports');

describe('Transform: <PivotPreview />', () => {
test('Minimal initialization', () => {
// Using the async/await wait()/done() pattern to avoid act() errors.
test('Minimal initialization', async done => {
// Arrange
const groupBy: PivotGroupByConfig = {
agg: PIVOT_SUPPORTED_GROUP_BY_AGGS.TERMS,
Expand All @@ -48,7 +49,6 @@ describe('Transform: <PivotPreview />', () => {
query: getPivotQuery('the-query'),
};

const Providers = getAppProviders({});
const { getByText } = render(
<Providers>
<PivotPreview {...props} />
Expand All @@ -58,5 +58,7 @@ describe('Transform: <PivotPreview />', () => {
// Act
// Assert
expect(getByText('Transform pivot preview')).toBeInTheDocument();
await wait();
done();
});
});
Loading

0 comments on commit 5a07ca7

Please sign in to comment.