Skip to content

Commit

Permalink
[ML] Fix tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Sep 23, 2020
1 parent d9501ad commit 59826c9
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 25 deletions.
4 changes: 4 additions & 0 deletions x-pack/plugins/ml/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,7 @@ export { ANOMALY_SEVERITY } from '../common';
export const getShared = async () => {
return await import('./shared');
};

// Helper to get Type returned by getShared.
type AwaitReturnType<T> = T extends PromiseLike<infer U> ? U : T;
export type GetSharedReturnType = AwaitReturnType<ReturnType<typeof getShared>>;
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { useContext } from 'react';

import { coreMock } from '../../../../../../src/core/public/mocks';
import { dataPluginMock } from '../../../../../../src/plugins/data/public/mocks';
import { Storage } from '../../../../../../src/plugins/kibana_utils/public';

import { MlSharedContext } from './shared_context';

const coreSetup = coreMock.createSetup();
const coreStart = coreMock.createStart();
const dataStart = dataPluginMock.createStartContract();
Expand All @@ -26,7 +30,8 @@ const appDependencies = {
};

export const useAppDependencies = () => {
return appDependencies;
const ml = useContext(MlSharedContext);
return { ...appDependencies, ml };
};

export const useToastNotifications = () => {
Expand Down
13 changes: 13 additions & 0 deletions x-pack/plugins/transform/public/app/__mocks__/shared_context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* 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.
*/

import { createContext } from 'react';

import { GetSharedReturnType } from '../../shared_imports';

// This code is a workaround to provide dependencies that are
// loaded dynamically during runtime.
export const MlSharedContext = createContext({} as GetSharedReturnType);
6 changes: 2 additions & 4 deletions x-pack/plugins/transform/public/app/app_dependencies.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ import { ScopedHistory } from 'kibana/public';
import { useKibana } from '../../../../../src/plugins/kibana_react/public';
import { Storage } from '../../../../../src/plugins/kibana_utils/public';

import { getShared } from '../shared_imports';

type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
import type { GetSharedReturnType } from '../shared_imports';

export interface AppDependencies {
chrome: CoreStart['chrome'];
Expand All @@ -27,7 +25,7 @@ export interface AppDependencies {
storage: Storage;
overlays: CoreStart['overlays'];
history: ScopedHistory;
ml: ThenArg<ReturnType<typeof getShared>>;
ml: GetSharedReturnType;
}

export const useAppDependencies = () => {
Expand Down
45 changes: 32 additions & 13 deletions x-pack/plugins/transform/public/app/hooks/use_index_data.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React from 'react';
import React, { FC } from 'react';

import { render, wait } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';

import { CoreSetup } from 'src/core/public';

import { DataGrid, UseIndexDataReturnType, INDEX_STATUS } from '../../shared_imports';
import { getShared, UseIndexDataReturnType } from '../../shared_imports';

import { SimpleQuery } from '../common';

Expand All @@ -22,6 +22,9 @@ jest.mock('../../shared_imports');
jest.mock('../app_dependencies');
jest.mock('./use_api');

import { useAppDependencies } from '../__mocks__/app_dependencies';
import { MlSharedContext } from '../__mocks__/shared_context';

const query: SimpleQuery = {
query_string: {
query: '*',
Expand All @@ -31,22 +34,29 @@ const query: SimpleQuery = {

describe('Transform: useIndexData()', () => {
test('indexPattern set triggers loading', async (done) => {
const { result, waitForNextUpdate } = renderHook(() =>
useIndexData(
({
id: 'the-id',
title: 'the-title',
fields: [],
} as unknown) as SearchItems['indexPattern'],
query
)
const mlShared = await getShared();
const wrapper: FC = ({ children }) => (
<MlSharedContext.Provider value={mlShared}>{children}</MlSharedContext.Provider>
);

const { result, waitForNextUpdate } = renderHook(
() =>
useIndexData(
({
id: 'the-id',
title: 'the-title',
fields: [],
} as unknown) as SearchItems['indexPattern'],
query
),
{ wrapper }
);
const IndexObj: UseIndexDataReturnType = result.current;

await waitForNextUpdate();

expect(IndexObj.errorMessage).toBe('');
expect(IndexObj.status).toBe(INDEX_STATUS.LOADING);
expect(IndexObj.status).toBe(1);
expect(IndexObj.tableItems).toEqual([]);
done();
});
Expand All @@ -61,7 +71,12 @@ describe('Transform: <DataGrid /> with useIndexData()', () => {
fields: [] as any[],
} as SearchItems['indexPattern'];

const mlShared = await getShared();

const Wrapper = () => {
const {
ml: { DataGrid },
} = useAppDependencies();
const props = {
...useIndexData(indexPattern, { match_all: {} }),
copyToClipboard: 'the-copy-to-clipboard-code',
Expand All @@ -73,7 +88,11 @@ describe('Transform: <DataGrid /> with useIndexData()', () => {

return <DataGrid {...props} />;
};
const { getByText } = render(<Wrapper />);
const { getByText } = render(
<MlSharedContext.Provider value={mlShared}>
<Wrapper />
</MlSharedContext.Provider>
);

// Act
// Assert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ import { StepDefineForm } from './step_define_form';
jest.mock('../../../../../shared_imports');
jest.mock('../../../../../app/app_dependencies');

import { MlSharedContext } from '../../../../../app/__mocks__/shared_context';
import { getShared } from '../../../../../shared_imports';

const createMockWebStorage = () => ({
clear: jest.fn(),
getItem: jest.fn(),
Expand All @@ -51,6 +54,8 @@ describe('Transform: <DefinePivotForm />', () => {
// Using the async/await wait()/done() pattern to avoid act() errors.
test('Minimal initialization', async (done) => {
// Arrange
const mlShared = await getShared();

const searchItems = {
indexPattern: {
title: 'the-index-pattern-title',
Expand All @@ -69,7 +74,9 @@ describe('Transform: <DefinePivotForm />', () => {
const { getByLabelText } = render(
<I18nProvider>
<KibanaContextProvider services={services}>
<StepDefineForm onChange={jest.fn()} searchItems={searchItems as SearchItems} />
<MlSharedContext.Provider value={mlShared}>
<StepDefineForm onChange={jest.fn()} searchItems={searchItems as SearchItems} />
</MlSharedContext.Provider>
</KibanaContextProvider>
</I18nProvider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,15 @@ import { StepDefineSummary } from './step_define_summary';
jest.mock('../../../../../shared_imports');
jest.mock('../../../../../app/app_dependencies');

import { MlSharedContext } from '../../../../../app/__mocks__/shared_context';
import { getShared } from '../../../../../shared_imports';

describe('Transform: <DefinePivotSummary />', () => {
// Using the async/await wait()/done() pattern to avoid act() errors.
test('Minimal initialization', async (done) => {
// Arrange
const mlShared = await getShared();

const searchItems = {
indexPattern: {
title: 'the-index-pattern-title',
Expand Down Expand Up @@ -57,7 +62,9 @@ describe('Transform: <DefinePivotSummary />', () => {
};

const { getByText } = render(
<StepDefineSummary formState={formState} searchItems={searchItems as SearchItems} />
<MlSharedContext.Provider value={mlShared}>
<StepDefineSummary formState={formState} searchItems={searchItems as SearchItems} />
</MlSharedContext.Provider>
);

// Act
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ import { ExpandedRow } from './expanded_row';
import transformListRow from '../../../../common/__mocks__/transform_list_row.json';
import { within } from '@testing-library/dom';

jest.mock('../../../../../shared_imports', () => ({
formatHumanReadableDateTimeSeconds: jest.fn(),
}));
jest.mock('../../../../../shared_imports');
jest.mock('../../../../../app/app_dependencies');

import { MlSharedContext } from '../../../../../app/__mocks__/shared_context';
import { getShared } from '../../../../../shared_imports';

describe('Transform: Transform List <ExpandedRow />', () => {
// Set timezone to US/Eastern for consistent test results.
beforeEach(() => {
Expand All @@ -27,9 +30,14 @@ describe('Transform: Transform List <ExpandedRow />', () => {
});

test('Minimal initialization', async () => {
const mlShared = await getShared();
const item: TransformListRow = transformListRow;

const { getByText, getByTestId } = render(<ExpandedRow item={item} />);
const { getByText, getByTestId } = render(
<MlSharedContext.Provider value={mlShared}>
<ExpandedRow item={item} />
</MlSharedContext.Provider>
);

expect(getByText('Details')).toBeInTheDocument();
expect(getByText('Stats')).toBeInTheDocument();
Expand Down
8 changes: 7 additions & 1 deletion x-pack/plugins/transform/public/shared_imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,10 @@ export {
useRequest,
} from '../../../../src/plugins/es_ui_shared/public';

export { getShared, UseIndexDataReturnType, EsSorting, RenderCellValue } from '../../ml/public';
export {
getShared,
GetSharedReturnType,
UseIndexDataReturnType,
EsSorting,
RenderCellValue,
} from '../../ml/public';

0 comments on commit 59826c9

Please sign in to comment.