Skip to content

Commit

Permalink
[Fleet] Use react testing libray instead of TestBed (#156301)
Browse files Browse the repository at this point in the history
  • Loading branch information
nchaulet authored May 2, 2023
1 parent eba1001 commit d41da82
Show file tree
Hide file tree
Showing 21 changed files with 163 additions and 252 deletions.
6 changes: 4 additions & 2 deletions x-pack/plugins/fleet/public/applications/fleet/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import type { FleetConfigType, FleetStartServices } from '../../plugin';

import { PackageInstallProvider } from '../integrations/hooks';

import { useAuthz, useFleetStatus, useFlyoutContext } from './hooks';
import { type FleetStatusProviderProps, useAuthz, useFleetStatus, useFlyoutContext } from './hooks';

import {
ConfigContext,
Expand Down Expand Up @@ -240,6 +240,7 @@ export const FleetAppContext: React.FC<{
theme$: AppMountParameters['theme$'];
/** For testing purposes only */
routerHistory?: History<any>;
fleetStatus?: FleetStatusProviderProps;
}> = memo(
({
children,
Expand All @@ -250,6 +251,7 @@ export const FleetAppContext: React.FC<{
extensions,
routerHistory,
theme$,
fleetStatus,
}) => {
const isDarkMode = useObservable<boolean>(startServices.uiSettings.get$('theme:darkMode'));

Expand All @@ -265,7 +267,7 @@ export const FleetAppContext: React.FC<{
<QueryClientProvider client={queryClient}>
<ReactQueryDevtools initialIsOpen={false} />
<UIExtensionsContext.Provider value={extensions}>
<FleetStatusProvider>
<FleetStatusProvider defaultFleetStatus={fleetStatus}>
<Router history={history}>
<PackageInstallProvider
notifications={startServices.notifications}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ const mockedUseGetPipeline = useGetPipeline as jest.MockedFunction<typeof useGet
jest.mock('../../../../hooks', () => {
return {
...jest.requireActual('../../../../hooks'),
FleetStatusProvider: (props: any) => {
return props.children;
},
useFleetStatus: jest.fn().mockReturnValue({ isReady: true } as any),
useGetPipeline: jest.fn(),
};
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,6 @@ import type { RegistryDataStream } from '../../../../../../../../../common/types

import { ExperimentDatastreamSettings } from './experimental_datastream_settings';

jest.mock('../../../../../../../../hooks', () => {
return {
...jest.requireActual('../../../../../../../../hooks'),
FleetStatusProvider: (props: any) => {
return props.children;
},
useFleetStatus: jest.fn().mockReturnValue({ isReady: true } as any),
sendGetStatus: jest
.fn()
.mockResolvedValue({ data: { isReady: true, missing_requirements: [] } }),
};
});

describe('ExperimentDatastreamSettings', () => {
describe('Synthetic source', () => {
it('should be enabled an not checked by default', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ import { useAuthz } from '../../../../../../hooks/use_authz';

import { AgentDetailsActionMenu } from './actions_menu';

jest.mock('../../../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
}));

jest.mock('../../../../../../services/experimental_features');
jest.mock('../../../../../../hooks/use_authz');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,12 @@

import React from 'react';

import { ThemeProvider } from 'styled-components';

import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';

import { coreMock } from '@kbn/core/public/mocks';
import { registerTestBed } from '@kbn/test-jest-helpers';

import type { Agent } from '../../../../types';

import { FleetStatusProvider, ConfigContext, KibanaVersionContext } from '../../../../../../hooks';

import { getMockTheme } from '../../../../../../mocks';

import { createFleetTestRendererMock } from '../../../../../../mock';
import { ExperimentalFeaturesService } from '../../../../services';

import { SearchAndFilterBar } from './search_and_filter_bar';

const mockTheme = getMockTheme({
eui: {
euiSize: '10px',
},
});

jest.mock('../../../../components', () => {
return {
SearchBar: () => <div />,
Expand All @@ -41,31 +24,24 @@ jest.mock('../../../../../../hooks/use_locator', () => {
useDashboardLocator: jest.fn().mockImplementation(() => {
return {
id: 'DASHBOARD_APP_LOCATOR',
getRedirectUrl: jest.fn().mockResolvedValue('app/dashboards#/view/elastic_agent-a0002'),
getRedirectUrl: jest.fn().mockReturnValue('app/dashboards#/view/elastic_agent-a0002'),
};
}),
};
});

const TestComponent = (props: any) => (
<KibanaContextProvider services={coreMock.createStart()}>
<ConfigContext.Provider value={{ agents: { enabled: true, elasticsearch: {} }, enabled: true }}>
<KibanaVersionContext.Provider value={'8.2.0'}>
<ThemeProvider theme={mockTheme}>
<FleetStatusProvider>
<SearchAndFilterBar {...props} />
</FleetStatusProvider>
</ThemeProvider>
</KibanaVersionContext.Provider>
</ConfigContext.Provider>
</KibanaContextProvider>
);

describe('SearchAndFilterBar', () => {
beforeAll(() => {
// @ts-ignore - prevents us needing to mock the entire service
ExperimentalFeaturesService.init({});
});

function render(props: any) {
const renderer = createFleetTestRendererMock();

return renderer.render(<SearchAndFilterBar {...props} />);
}

it('should show no Actions button when no agent is selected', async () => {
const selectedAgents: Agent[] = [];
const props: any = {
Expand All @@ -83,10 +59,8 @@ describe('SearchAndFilterBar', () => {
selectedAgentPolicies: [],
showAgentActivityTour: {},
};
const testBed = registerTestBed(TestComponent)(props);
const { exists } = testBed;

expect(exists('agentBulkActionsButton')).toBe(false);
const results = render(props);
expect(results.queryByTestId('agentBulkActionsButton')).toBeNull();
});

it('should show an Actions button when at least an agent is selected', async () => {
Expand Down Expand Up @@ -117,10 +91,8 @@ describe('SearchAndFilterBar', () => {
selectedAgentPolicies: [],
showAgentActivityTour: {},
};
const testBed = registerTestBed(TestComponent)(props);
const { exists } = testBed;

expect(exists('agentBulkActionsButton')).not.toBeNull();
const results = render(props);
expect(results.queryByTestId('agentBulkActionsButton')).not.toBeNull();
});

it('should show an Actions button when agents selected in query mode', async () => {
Expand All @@ -139,9 +111,7 @@ describe('SearchAndFilterBar', () => {
selectedAgentPolicies: [],
showAgentActivityTour: {},
};
const testBed = registerTestBed(TestComponent)(props);
const { exists } = testBed;

expect(exists('agentBulkActionsButton')).not.toBeNull();
const results = render(props);
expect(results.queryByTestId('agentBulkActionsButton')).not.toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const ClearAllTagsFilterItem = styled(EuiFilterSelectItem)`
padding: ${(props) => props.theme.eui.euiSizeS};
`;

export const SearchAndFilterBar: React.FunctionComponent<{
export interface SearchAndFilterBarProps {
agentPolicies: AgentPolicy[];
draftKuery: string;
onDraftKueryChange: (kuery: string) => void;
Expand All @@ -62,7 +62,9 @@ export const SearchAndFilterBar: React.FunctionComponent<{
visibleAgents: Agent[];
onClickAgentActivity: () => void;
showAgentActivityTour: { isOpen: boolean };
}> = ({
}

export const SearchAndFilterBar: React.FunctionComponent<SearchAndFilterBarProps> = ({
agentPolicies,
draftKuery,
onDraftKueryChange,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ import { useAuthz } from '../../../../../../hooks/use_authz';

import { TableRowActions } from './table_row_actions';

jest.mock('../../../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
}));

jest.mock('../../../../../../services/experimental_features');
jest.mock('../../../../../../hooks/use_authz');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,6 @@ import { createFleetTestRendererMock } from '../../../../../../mock';

import { useScheduleDateTime } from './hooks';

jest.mock('../../../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
useFleetStatus: jest.fn().mockReturnValue({}),
}));

describe('useScheduleDateTime', () => {
it('do not allow to set a date before the current time', async () => {
const renderer = createFleetTestRendererMock();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,6 @@ import { createFleetTestRendererMock } from '../../../../../../mock';
import { AgentUpgradeAgentModal } from '.';
import type { AgentUpgradeAgentModalProps } from '.';

jest.mock('../../../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
useFleetStatus: jest.fn().mockReturnValue({}),
}));

jest.mock('@elastic/eui', () => {
return {
...jest.requireActual('@elastic/eui'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import { useAuthz } from '../../../../hooks/use_authz';
import { AgentsApp } from '.';

jest.mock('../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
...jest.requireActual('../../../../hooks/use_fleet_status'),
useFleetStatus: jest.fn().mockReturnValue({}),
}));
jest.mock('../../../../hooks/use_request/settings');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,6 @@ import { createFleetTestRendererMock } from '../../../../../../mock';

import { EditDownloadSourceFlyout } from '.';

jest.mock('../../../../../../hooks/use_fleet_status', () => ({
FleetStatusProvider: (props: any) => {
return props.children;
},
useFleetStatus: jest.fn().mockReturnValue({}),
}));

function renderFlyout(downloadSource?: DownloadSource) {
const renderer = createFleetTestRendererMock();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type { FleetConfigType, FleetStartServices } from '../../plugin';
import {
ConfigContext,
FleetStatusProvider,
type FleetStatusProviderProps,
KibanaVersionContext,
useFleetStatus,
} from '../../hooks';
Expand Down Expand Up @@ -61,6 +62,7 @@ export const IntegrationsAppContext: React.FC<{
theme$: AppMountParameters['theme$'];
/** For testing purposes only */
routerHistory?: History<any>; // TODO remove
fleetStatus?: FleetStatusProviderProps;
}> = memo(
({
children,
Expand All @@ -71,6 +73,7 @@ export const IntegrationsAppContext: React.FC<{
extensions,
setHeaderActionMenu,
theme$,
fleetStatus,
}) => {
const isDarkMode = useObservable<boolean>(startServices.uiSettings.get$('theme:darkMode'));
const CloudContext = startServices.cloud?.CloudContextProvider || EmptyContext;
Expand All @@ -87,7 +90,7 @@ export const IntegrationsAppContext: React.FC<{
<QueryClientProvider client={queryClient}>
<ReactQueryDevtools initialIsOpen={false} />
<UIExtensionsContext.Provider value={extensions}>
<FleetStatusProvider>
<FleetStatusProvider defaultFleetStatus={fleetStatus}>
<startServices.customIntegrations.ContextProvider>
<CloudContext>
<Router history={history}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
* 2.0.
*/

import React from 'react';
// TODO(jbudz): should be removed when upgrading to TS@4.8
// this is a skip for the errors created when typechecking with isolatedModules
export {};

jest.mock('../../hooks', () => {
return {
...jest.requireActual('../../hooks'),
useFleetStatus: jest.fn(),
useFleetServerStandalone: jest.fn(),
useAgentEnrollmentFlyoutData: jest.fn(),
};
Expand Down Expand Up @@ -96,14 +96,28 @@ jest.mock('./steps', () => {
AgentPolicySelectionStep: jest.fn().mockReturnValue({
'data-test-subj': 'agent-policy-selection-step',
title: 'agent-policy-selection-step',
children: <>TEST</>,
}),
AgentEnrollmentKeySelectionStep: jest.fn().mockReturnValue({
'data-test-subj': 'agent-enrollment-key-selection-step',
title: 'agent-enrollment-key-selection-step',
children: <>TEST</>,
}),
ConfigureStandaloneAgentStep: jest.fn().mockReturnValue({
'data-test-subj': 'configure-standalone-step',
title: 'configure-standalone-step',
children: <>TEST</>,
}),
DownloadStep: jest.fn().mockReturnValue({
'data-test-subj': 'download-step',
title: 'download-step',
children: <>TEST</>,
}),
IncomingDataConfirmationStep: jest.fn().mockReturnValue({
'data-test-subj': 'incoming-data-confirmation-step',
title: 'incoming-data-confirmation-step',
children: <>TEST</>,
}),
DownloadStep: jest
.fn()
.mockReturnValue({ 'data-test-subj': 'download-step', title: 'download-step' }),
};
});

Expand Down
Loading

0 comments on commit d41da82

Please sign in to comment.