Fix tests

This commit is contained in:
Ivan Shmidt
2020-06-04 16:50:05 +02:00
parent 947cb2984e
commit 3cc59f3276
9 changed files with 306 additions and 118 deletions
@@ -20,9 +20,22 @@ import CatalogPage from './CatalogPage';
import { ApiRegistry, ApiProvider, errorApiRef } from '@backstage/core';
import { wrapInTestApp } from '@backstage/test-utils';
import { catalogApiRef } from '../..';
import { CatalogApi } from '../../api/types';
import { Entity } from '@backstage/catalog-model';
const errorApi = { post: () => {} };
const catalogApi = { getEntities: () => Promise.resolve([{ kind: '' }]) };
const catalogApi: Partial<CatalogApi> = {
getEntities: () =>
Promise.resolve([
{
metadata: {
name: 'Entity1',
},
apiVersion: 'backstage.io/v1beta1',
kind: 'Component',
},
] as Entity[]),
};
describe('CatalogPage', () => {
// this test right now causes some red lines in the log output when running tests
+1
View File
@@ -18,6 +18,7 @@
},
"dependencies": {
"@backstage/core": "^0.1.1-alpha.6",
"@backstage/catalog-model": "^0.1.1-alpha.6",
"@backstage/plugin-catalog": "^0.1.1-alpha.6",
"@backstage/theme": "^0.1.1-alpha.6",
"@material-ui/core": "^4.9.1",
@@ -15,16 +15,29 @@
*/
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import RegisterComponentForm from './RegisterComponentForm';
import { render, fireEvent, cleanup } from '@testing-library/react';
import RegisterComponentForm, { Props } from './RegisterComponentForm';
import { act } from 'react-dom/test-utils';
// TODO(ishmidt): rewrite tests
const setup = (props?: Partial<Props>) => {
return {
rendered: render(
<RegisterComponentForm
onSubmit={jest.fn()}
submitting={false}
{...props}
/>,
),
};
};
describe('RegisterComponentForm', () => {
afterEach(() => cleanup());
it('should initially render a disabled button', async () => {
const rendered = render(<RegisterComponentForm onSubmit={jest.fn()} />);
const { rendered } = setup();
expect(
await rendered.findByText(
'Enter the full path to the service-info.yaml file in GHE to start tracking your component. It must be in a public repo, on the master branch.',
'Enter the full path to the service-info.yaml file in GitHub to start tracking your component. It must be in a public repo.',
),
).toBeInTheDocument();
@@ -33,23 +46,21 @@ describe('RegisterComponentForm', () => {
});
it('should enable a submit form when data when component url is set ', async () => {
const rendered = render(<RegisterComponentForm onSubmit={jest.fn()} />);
const { rendered } = setup();
const input = (await rendered.getByRole('textbox')) as HTMLInputElement;
fireEvent.change(input, {
target: { value: 'https://example.com/blob/master/service.yaml' },
await act(async () => {
// react-hook-form uses `input` event for changes
fireEvent.input(input, {
target: { value: 'https://example.com/blob/master/service.yaml' },
});
});
const submit = (await rendered.findByText('Submit')) as HTMLButtonElement;
const submit = (await rendered.getByRole('button')) as HTMLButtonElement;
expect(submit.disabled).toBeFalsy();
});
it('should hide input on submission ', async () => {
const rendered = render(<RegisterComponentForm onSubmit={jest.fn()} />);
expect(
await rendered.findByText(
'Your component is being registered. Please wait.',
),
).toBeInTheDocument();
});
});
it('should show spinner while submitting', async () => {
const { rendered } = setup({ submitting: true });
expect(rendered.getByTestId('loading-progress')).toBeInTheDocument();
});
@@ -20,6 +20,7 @@ import {
FormControl,
FormHelperText,
TextField,
LinearProgress,
} from '@material-ui/core';
import { useForm } from 'react-hook-form';
import { makeStyles } from '@material-ui/core/styles';
@@ -37,11 +38,12 @@ const useStyles = makeStyles<BackstageTheme>(theme => ({
},
}));
type RegisterComponentProps = {
export type Props = {
onSubmit: (formData: Record<string, string>) => Promise<void>;
submitting: boolean;
};
const RegisterComponentForm: FC<RegisterComponentProps> = ({ onSubmit }) => {
const RegisterComponentForm: FC<Props> = ({ onSubmit, submitting }) => {
const { register, handleSubmit, errors, formState } = useForm({
mode: 'onChange',
});
@@ -49,23 +51,27 @@ const RegisterComponentForm: FC<RegisterComponentProps> = ({ onSubmit }) => {
const hasErrors = !!errors.componentLocation;
const dirty = formState?.dirty;
return (
return submitting ? (
<LinearProgress data-testid="loading-progress" />
) : (
<form
autoComplete="off"
onSubmit={handleSubmit(onSubmit)}
className={classes.form}
data-testid="register-form"
>
<FormControl>
<TextField
id="registerComponentInput"
variant="outlined"
label="Component service file URL"
data-testid="componentLocationInput"
error={hasErrors}
placeholder="https://example.com/user/some-service/blob/master/service-info.yaml"
name="componentLocation"
required
margin="normal"
helperText="Enter the full path to the service-info.yaml file in GHE to start tracking your component. It must be in a public repo, on the master branch."
helperText="Enter the full path to the service-info.yaml file in GitHub to start tracking your component. It must be in a public repo."
inputRef={register({
required: true,
validate: ComponentIdValidators,
@@ -15,20 +15,45 @@
*/
import React from 'react';
import { render } from '@testing-library/react';
import mockFetch from 'jest-fetch-mock';
import { render, cleanup } from '@testing-library/react';
import RegisterComponentPage from './RegisterComponentPage';
import { ThemeProvider } from '@material-ui/core';
import { lightTheme } from '@backstage/theme';
import { errorApiRef, ApiProvider, ApiRegistry } from '@backstage/core';
import { catalogApiRef } from '@backstage/plugin-catalog';
import { MemoryRouter } from 'react-router-dom';
const errorApi = { post: () => {} };
const catalogApi: jest.Mocked<typeof catalogApiRef.T> = {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
addLocation: jest.fn((_a, _b) => new Promise(() => {})),
getEntities: jest.fn(),
getEntityByName: jest.fn(),
};
const setup = () => ({
rendered: render(
<MemoryRouter>
<ApiProvider
apis={ApiRegistry.from([
[errorApiRef, errorApi],
[catalogApiRef, catalogApi],
])}
>
<ThemeProvider theme={lightTheme}>
<RegisterComponentPage />
</ThemeProvider>
</ApiProvider>
</MemoryRouter>,
),
});
describe('RegisterComponentPage', () => {
afterEach(() => cleanup());
it('should render', () => {
mockFetch.mockResponse(() => new Promise(() => {}));
const rendered = render(
<ThemeProvider theme={lightTheme}>
<RegisterComponentPage />
</ThemeProvider>,
);
expect(rendered.getByText('Register Component')).toBeInTheDocument();
const { rendered } = setup();
expect(
rendered.getByText('Register existing component'),
).toBeInTheDocument();
});
});
@@ -15,22 +15,7 @@
*/
import React, { FC, useState } from 'react';
import { Link as RouterLink } from 'react-router-dom';
import {
Grid,
makeStyles,
DialogTitle,
Dialog,
DialogContent,
DialogContentText,
DialogActions,
Button,
ListItem,
List,
LinearProgress,
Divider,
Link,
} from '@material-ui/core';
import { Grid, makeStyles } from '@material-ui/core';
import {
InfoCard,
Page,
@@ -38,16 +23,13 @@ import {
Content,
useApi,
errorApiRef,
StructuredMetadataTable,
Header,
} from '@backstage/core';
import RegisterComponentForm from '../RegisterComponentForm';
import {
entityRoute,
rootRoute as catalogRootRoute,
catalogApiRef
} from '@backstage/plugin-catalog';
import { generatePath } from 'react-router';
import { catalogApiRef } from '@backstage/plugin-catalog';
import { useMountedState } from 'react-use';
import { Entity, Location } from '@backstage/catalog-model';
import { RegisterComponentResultDialog } from '../RegisterComponentResultDialog';
const useStyles = makeStyles(theme => ({
dialogPaper: {
@@ -76,11 +58,15 @@ const RegisterComponentPage: FC<{}> = () => {
const [formState, setFormState] = useState<ValuesOf<typeof FormStates>>(
FormStates.Idle,
);
const isMounted = useMountedState();
const errorApi = useApi(errorApiRef);
const [result, setResult] = useState<{
data: any;
data: {
entities: Entity[];
location: Location;
} | null;
error: null | Error;
}>({
data: null,
@@ -93,12 +79,17 @@ const RegisterComponentPage: FC<{}> = () => {
try {
const data = await catalogApi.addLocation('github', target);
if (!isMounted()) return;
setResult({ error: null, data });
setFormState(FormStates.Success);
} catch (e) {
errorApi.post(e);
if (!isMounted()) return;
setResult({ error: e, data: null });
setFormState(FormStates.Idle);
errorApi.post(e);
}
};
@@ -109,70 +100,21 @@ const RegisterComponentPage: FC<{}> = () => {
<Grid container spacing={3} direction="column">
<Grid item>
<InfoCard title="Start tracking your component in Backstage">
{formState === FormStates.Submitting ? (
<LinearProgress />
) : (
<RegisterComponentForm onSubmit={handleSubmit} />
)}
<RegisterComponentForm
onSubmit={handleSubmit}
submitting={formState === FormStates.Submitting}
/>
</InfoCard>
</Grid>
</Grid>
</Content>
<Dialog
open={formState === FormStates.Success}
onClose={() => setFormState(FormStates.Idle)}
classes={{ paper: classes.dialogPaper }}
>
<DialogTitle>Component registration result</DialogTitle>
{formState === FormStates.Success && (
<>
<DialogContent>
<DialogContentText>
Following components have been succefully created:
<List>
{result.data.entities.map((entity: any, index: number) => (
<>
<ListItem>
<StructuredMetadataTable
dense
metadata={{
name: entity.metadata.name,
type: entity.spec.type,
link: (
<Link
component={RouterLink}
to={generatePath(entityRoute.path, {
name: entity.metadata.name,
})}
>
{generatePath(entityRoute.path, {
name: entity.metadata.name,
})}
</Link>
),
}}
/>
</ListItem>
{index < result.data.entities.length - 1 && (
<Divider component="li" />
)}
</>
))}
</List>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
component={RouterLink}
to={catalogRootRoute.path}
color="default"
>
To Catalog
</Button>
</DialogActions>
</>
)}
</Dialog>
{formState === FormStates.Success && (
<RegisterComponentResultDialog
entities={result.data!.entities}
onClose={() => setFormState(FormStates.Idle)}
classes={{ paper: classes.dialogPaper }}
/>
)}
</Page>
);
};
@@ -0,0 +1,80 @@
/*
* Copyright 2020 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { ComponentProps } from 'react';
import { render, cleanup } from '@testing-library/react';
import { RegisterComponentResultDialog } from './RegisterComponentResultDialog';
import { ThemeProvider } from '@material-ui/core';
import { lightTheme } from '@backstage/theme';
import { MemoryRouter } from 'react-router-dom';
import { Entity } from '@backstage/catalog-model';
const setup = (
props?: Partial<ComponentProps<typeof RegisterComponentResultDialog>>,
) => ({
rendered: render(
<MemoryRouter>
<ThemeProvider theme={lightTheme}>
<RegisterComponentResultDialog
onClose={() => {}}
entities={[]}
{...props}
/>
</ThemeProvider>
</MemoryRouter>,
),
});
describe('RegisterComponentResultDialog', () => {
afterEach(() => cleanup());
it('should render', () => {
const { rendered } = setup();
expect(
rendered.getByText('Component registration result'),
).toBeInTheDocument();
});
});
it('should show a list of components if success', async () => {
const { rendered } = setup({
entities: [
{
kind: 'Component',
metadata: {
name: 'Component1',
},
spec: {
type: 'website',
},
},
{
kind: 'Component',
metadata: {
name: 'Component2',
},
spec: {
type: 'service',
},
},
] as Entity[],
});
expect(
rendered.getByText('Following components have been succefully created:'),
).toBeInTheDocument();
expect(rendered.getByText('Component1')).toBeInTheDocument();
expect(rendered.getByText('Component2')).toBeInTheDocument();
});
@@ -0,0 +1,93 @@
/*
* Copyright 2020 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { FC } from 'react';
import {
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
List,
ListItem,
Link,
Divider,
DialogActions,
Button,
} from '@material-ui/core';
import { Entity } from '@backstage/catalog-model';
import { StructuredMetadataTable } from '@backstage/core';
import { generatePath } from 'react-router';
import {
entityRoute,
rootRoute as catalogRootRoute,
} from '@backstage/plugin-catalog';
import { Link as RouterLink } from 'react-router-dom';
type Props = {
onClose: () => void;
classes?: Record<string, string>;
entities: Entity[];
};
export const RegisterComponentResultDialog: FC<Props> = ({
onClose,
classes,
entities,
}) => (
<Dialog open onClose={onClose} classes={classes}>
<DialogTitle>Component registration result</DialogTitle>
<DialogContent>
<DialogContentText>
Following components have been succefully created:
</DialogContentText>
<List>
{entities.map((entity: any, index: number) => (
<React.Fragment
key={`${entity.metadata.namespace}-${entity.metadata.name}`}
>
<ListItem>
<StructuredMetadataTable
dense
metadata={{
name: entity.metadata.name,
type: entity.spec.type,
link: (
<Link
component={RouterLink}
to={generatePath(entityRoute.path, {
name: entity.metadata.name,
})}
>
{generatePath(entityRoute.path, {
name: entity.metadata.name,
})}
</Link>
),
}}
/>
</ListItem>
{index < entities.length - 1 && <Divider component="li" />}
</React.Fragment>
))}
</List>
</DialogContent>
<DialogActions>
<Button component={RouterLink} to={catalogRootRoute.path} color="default">
To Catalog
</Button>
</DialogActions>
</Dialog>
);
@@ -0,0 +1,17 @@
/*
* Copyright 2020 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { RegisterComponentResultDialog } from './RegisterComponentResultDialog';