Merge remote-tracking branch 'origin/master' into scaffolder-result-content

# Conflicts:
#	plugins/scaffolder/src/components/TemplatePage/TemplatePage.tsx
This commit is contained in:
bogdannechyporenko
2022-11-21 21:27:32 +01:00
184 changed files with 3896 additions and 2580 deletions
@@ -46,7 +46,7 @@ describe('BitriseArtifactsComponent', () => {
const rendered = renderComponent();
const btn = await rendered.findByTestId('btn');
expect(await rendered.queryByText('VISIBLE')).not.toBeInTheDocument();
expect(rendered.queryByText('VISIBLE')).not.toBeInTheDocument();
btn.click();
+14 -13
View File
@@ -37,7 +37,7 @@ import { EntityRelationSpec } from '@backstage/plugin-catalog-node';
import { GetEntitiesRequest } from '@backstage/catalog-client';
import { JsonValue } from '@backstage/types';
import { LocationEntityV1alpha1 } from '@backstage/catalog-model';
import { LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec as LocationSpec_2 } from '@backstage/plugin-catalog-common';
import { Logger } from 'winston';
import { Permission } from '@backstage/plugin-permission-common';
import { PermissionAuthorizer } from '@backstage/plugin-permission-common';
@@ -86,9 +86,9 @@ export class AnnotateLocationEntityProcessor implements CatalogProcessor {
// (undocumented)
preProcessEntity(
entity: Entity,
location: LocationSpec,
location: LocationSpec_2,
_: CatalogProcessorEmit,
originLocation: LocationSpec,
originLocation: LocationSpec_2,
): Promise<Entity>;
}
@@ -100,7 +100,7 @@ export class AnnotateScmSlugEntityProcessor implements CatalogProcessor {
// (undocumented)
getProcessorName(): string;
// (undocumented)
preProcessEntity(entity: Entity, location: LocationSpec): Promise<Entity>;
preProcessEntity(entity: Entity, location: LocationSpec_2): Promise<Entity>;
}
// @public (undocumented)
@@ -110,7 +110,7 @@ export class BuiltinKindsEntityProcessor implements CatalogProcessor {
// (undocumented)
postProcessEntity(
entity: Entity,
_location: LocationSpec,
_location: LocationSpec_2,
emit: CatalogProcessorEmit,
): Promise<Entity>;
// (undocumented)
@@ -284,7 +284,7 @@ export class CodeOwnersProcessor implements CatalogProcessor {
// (undocumented)
getProcessorName(): string;
// (undocumented)
preProcessEntity(entity: Entity, location: LocationSpec): Promise<Entity>;
preProcessEntity(entity: Entity, location: LocationSpec_2): Promise<Entity>;
}
// @alpha
@@ -409,7 +409,7 @@ export class FileReaderProcessor implements CatalogProcessor {
getProcessorName(): string;
// (undocumented)
readLocation(
location: LocationSpec,
location: LocationSpec_2,
optional: boolean,
emit: CatalogProcessorEmit,
parser: CatalogProcessorParser,
@@ -431,7 +431,7 @@ export class LocationEntityProcessor implements CatalogProcessor {
// (undocumented)
postProcessEntity(
entity: Entity,
location: LocationSpec,
location: LocationSpec_2,
emit: CatalogProcessorEmit,
): Promise<Entity>;
}
@@ -441,18 +441,19 @@ export type LocationEntityProcessorOptions = {
integrations: ScmIntegrationRegistry;
};
export { LocationSpec };
// @public @deprecated
export type LocationSpec = LocationSpec_2;
// @public (undocumented)
export function locationSpecToLocationEntity(opts: {
location: LocationSpec;
location: LocationSpec_2;
parentEntity?: Entity;
}): LocationEntityV1alpha1;
// @public (undocumented)
export function parseEntityYaml(
data: Buffer,
location: LocationSpec,
location: LocationSpec_2,
): Iterable<CatalogProcessorResult>;
// @alpha
@@ -518,7 +519,7 @@ export class PlaceholderProcessor implements CatalogProcessor {
// (undocumented)
preProcessEntity(
entity: Entity,
location: LocationSpec,
location: LocationSpec_2,
emit: CatalogProcessorEmit,
): Promise<Entity>;
}
@@ -574,7 +575,7 @@ export class UrlReaderProcessor implements CatalogProcessor {
getProcessorName(): string;
// (undocumented)
readLocation(
location: LocationSpec,
location: LocationSpec_2,
optional: boolean,
emit: CatalogProcessorEmit,
parser: CatalogProcessorParser,
@@ -80,6 +80,36 @@ export type EntitiesResponse = {
pageInfo: PageInfo;
};
/**
* A request for a batch of entities.
*/
export interface EntitiesBatchRequest {
/**
* The refs for which to fetch entities.
*/
entityRefs: string[];
/**
* Any additional filters to apply in the selection of the entities.
*/
filter?: EntityFilter;
/**
* Strips out only the parts of the entity bodies to include in the response.
*/
fields?: (entity: Entity) => Entity;
/**
* The optional token that authorizes the action.
*/
authorizationToken?: string;
}
export interface EntitiesBatchResponse {
/**
* The list of entities, in the same order as the refs in the request. Entries
* that are null signify that no entity existed with that ref.
*/
items: Array<Entity | null>;
}
export type EntityAncestryResponse = {
rootEntityRef: string;
items: Array<{
@@ -130,6 +160,11 @@ export interface EntitiesCatalog {
*/
entities(request?: EntitiesRequest): Promise<EntitiesResponse>;
/**
* Fetches a batch of entities.
*/
entitiesBatch(request: EntitiesBatchRequest): Promise<EntitiesBatchResponse>;
/**
* Removes a single entity.
*
+16 -1
View File
@@ -22,7 +22,6 @@
export type {
DeferredEntity,
LocationSpec,
EntityRelationSpec,
CatalogProcessor,
CatalogProcessorParser,
@@ -48,3 +47,19 @@ export * from './processing';
export * from './search';
export * from './service';
export * from './util';
import { LocationSpec as NonDeprecatedLocationSpec } from '@backstage/plugin-catalog-common';
/**
* Holds the entity location information.
*
* @remarks
*
* `presence` flag: when using repo importer plugin, location is being created before the component yaml file is merged to the main branch.
* This flag is then set to indicate that the file can be not present.
* default value: 'required'.
*
* @public
* @deprecated use the same type from `@backstage/plugin-catalog-common` instead
*/
export type LocationSpec = NonDeprecatedLocationSpec;
@@ -17,7 +17,7 @@
import { Config } from '@backstage/config';
import { Entity } from '@backstage/catalog-model';
import path from 'path';
import { LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec } from '@backstage/plugin-catalog-common';
/**
* Rules to apply to catalog entities.
@@ -22,7 +22,8 @@ import {
ScmIntegrations,
} from '@backstage/integration';
import { Logger } from 'winston';
import { CatalogProcessor, LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import { CatalogProcessor } from '@backstage/plugin-catalog-node';
import { findCodeOwnerByTarget } from './lib';
const ALLOWED_KINDS = ['API', 'Component', 'Domain', 'Resource', 'System'];
@@ -25,10 +25,10 @@ import {
} from '@backstage/catalog-model';
import { ScmIntegrationRegistry } from '@backstage/integration';
import { identity, merge, pickBy } from 'lodash';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorEmit,
LocationSpec,
} from '@backstage/plugin-catalog-node';
/** @public */
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Entity } from '@backstage/catalog-model';
import { Config } from '@backstage/config';
import {
@@ -21,7 +22,8 @@ import {
} from '@backstage/integration';
import parseGitUrl from 'git-url-parse';
import { identity, merge, pickBy } from 'lodash';
import { CatalogProcessor, LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import { CatalogProcessor } from '@backstage/plugin-catalog-node';
const GITHUB_ACTIONS_ANNOTATION = 'github.com/project-slug';
const GITLAB_ACTIONS_ANNOTATION = 'gitlab.com/project-slug';
@@ -48,10 +48,10 @@ import {
UserEntity,
userEntityV1alpha1Validator,
} from '@backstage/catalog-model';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorEmit,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
@@ -18,11 +18,11 @@ import fs from 'fs-extra';
import g from 'glob';
import path from 'path';
import { promisify } from 'util';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorEmit,
CatalogProcessorParser,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
@@ -17,11 +17,11 @@
import { Entity, LocationEntity } from '@backstage/catalog-model';
import { ScmIntegrationRegistry } from '@backstage/integration';
import path from 'path';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
processingResult,
CatalogProcessor,
CatalogProcessorEmit,
LocationSpec,
} from '@backstage/plugin-catalog-node';
export function toAbsoluteUrl(
@@ -19,10 +19,10 @@ import { Entity } from '@backstage/catalog-model';
import { JsonValue } from '@backstage/types';
import { ScmIntegrationRegistry } from '@backstage/integration';
import yaml from 'yaml';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorEmit,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
@@ -20,6 +20,7 @@ import { assertError } from '@backstage/errors';
import parseGitUrl from 'git-url-parse';
import limiterFactory from 'p-limit';
import { Logger } from 'winston';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorCache,
@@ -27,7 +28,6 @@ import {
CatalogProcessorEntityResult,
CatalogProcessorParser,
CatalogProcessorResult,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
@@ -17,10 +17,10 @@
import { Entity, stringifyLocationRef } from '@backstage/catalog-model';
import lodash from 'lodash';
import yaml from 'yaml';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessorParser,
CatalogProcessorResult,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
@@ -32,10 +32,10 @@ import { JsonValue } from '@backstage/types';
import { ScmIntegrationRegistry } from '@backstage/integration';
import path from 'path';
import { Logger } from 'winston';
import { LocationSpec } from '@backstage/plugin-catalog-common';
import {
CatalogProcessor,
CatalogProcessorParser,
LocationSpec,
processingResult,
} from '@backstage/plugin-catalog-node';
import {
@@ -27,7 +27,7 @@ import { JsonObject, JsonValue } from '@backstage/types';
import { InputError } from '@backstage/errors';
import { ScmIntegrationRegistry } from '@backstage/integration';
import path from 'path';
import { LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec } from '@backstage/plugin-catalog-common';
export function isLocationEntity(entity: Entity): entity is LocationEntity {
return entity.kind === 'Location';
@@ -24,6 +24,7 @@ import { AuthorizedEntitiesCatalog } from './AuthorizedEntitiesCatalog';
describe('AuthorizedEntitiesCatalog', () => {
const fakeCatalog = {
entities: jest.fn(),
entitiesBatch: jest.fn(),
removeEntityByUid: jest.fn(),
entityAncestry: jest.fn(),
facets: jest.fn(),
@@ -92,6 +93,67 @@ describe('AuthorizedEntitiesCatalog', () => {
});
});
describe('entitiesBatch', () => {
it('returns empty response on DENY', async () => {
fakePermissionApi.authorizeConditional.mockResolvedValue([
{ result: AuthorizeResult.DENY },
]);
const catalog = createCatalog();
await expect(
catalog.entitiesBatch({
entityRefs: ['component:default/component-a'],
authorizationToken: 'abcd',
}),
).resolves.toEqual({
items: [null],
});
expect(fakeCatalog.entitiesBatch).not.toHaveBeenCalled();
});
it('calls underlying catalog method with correct filter on CONDITIONAL', async () => {
fakePermissionApi.authorizeConditional.mockResolvedValue([
{
result: AuthorizeResult.CONDITIONAL,
conditions: {
rule: 'IS_ENTITY_KIND',
params: { kinds: ['b'] },
},
},
]);
const catalog = createCatalog(isEntityKind);
await catalog.entitiesBatch({
entityRefs: ['component:default/component-a'],
authorizationToken: 'abcd',
});
expect(fakeCatalog.entitiesBatch).toHaveBeenCalledWith({
entityRefs: ['component:default/component-a'],
authorizationToken: 'abcd',
filter: { key: 'kind', values: ['b'] },
});
});
it('calls underlying catalog method on ALLOW', async () => {
fakePermissionApi.authorizeConditional.mockResolvedValue([
{ result: AuthorizeResult.ALLOW },
]);
const catalog = createCatalog();
await catalog.entitiesBatch({
entityRefs: ['component:default/component-a'],
authorizationToken: 'abcd',
});
expect(fakeCatalog.entitiesBatch).toHaveBeenCalledWith({
entityRefs: ['component:default/component-a'],
authorizationToken: 'abcd',
});
});
});
describe('removeEntityByUid', () => {
it('throws error on DENY', async () => {
fakeCatalog.entities.mockResolvedValue({
@@ -26,6 +26,8 @@ import {
} from '@backstage/plugin-permission-common';
import { ConditionTransformer } from '@backstage/plugin-permission-node';
import {
EntitiesBatchRequest,
EntitiesBatchResponse,
EntitiesCatalog,
EntitiesRequest,
EntitiesResponse,
@@ -73,6 +75,37 @@ export class AuthorizedEntitiesCatalog implements EntitiesCatalog {
return this.entitiesCatalog.entities(request);
}
async entitiesBatch(
request: EntitiesBatchRequest,
): Promise<EntitiesBatchResponse> {
const authorizeDecision = (
await this.permissionApi.authorizeConditional(
[{ permission: catalogEntityReadPermission }],
{ token: request?.authorizationToken },
)
)[0];
if (authorizeDecision.result === AuthorizeResult.DENY) {
return {
items: new Array(request.entityRefs.length).fill(null),
};
}
if (authorizeDecision.result === AuthorizeResult.CONDITIONAL) {
const permissionFilter: EntityFilter = this.transformConditions(
authorizeDecision.conditions,
);
return this.entitiesCatalog.entitiesBatch({
...request,
filter: request?.filter
? { allOf: [permissionFilter, request.filter] }
: permissionFilter,
});
}
return this.entitiesCatalog.entitiesBatch(request);
}
async removeEntityByUid(
uid: string,
options?: { authorizationToken?: string },
@@ -22,6 +22,7 @@ import {
permissionsServiceRef,
urlReaderServiceRef,
httpRouterServiceRef,
lifecycleServiceRef,
} from '@backstage/backend-plugin-api';
import { CatalogBuilder } from './CatalogBuilder';
import {
@@ -78,6 +79,7 @@ export const catalogPlugin = createBackendPlugin({
permissions: permissionsServiceRef,
database: databaseServiceRef,
httpRouter: httpRouterServiceRef,
lifecycle: lifecycleServiceRef,
},
async init({
logger,
@@ -86,6 +88,7 @@ export const catalogPlugin = createBackendPlugin({
database,
permissions,
httpRouter,
lifecycle,
}) {
const winstonLogger = loggerToWinstonLogger(logger);
const builder = await CatalogBuilder.create({
@@ -100,7 +103,11 @@ export const catalogPlugin = createBackendPlugin({
const { processingEngine, router } = await builder.build();
await processingEngine.start();
lifecycle.addShutdownHook({
fn: async () => {
await processingEngine.stop();
},
});
httpRouter.use(router);
},
});
@@ -534,6 +534,60 @@ describe('DefaultEntitiesCatalog', () => {
);
});
describe('entitiesBatch', () => {
it.each(databases.eachSupportedId())(
'queries for entities by ref, including duplicates, and gracefully returns null for missing entities',
async databaseId => {
const { knex } = await createDatabase(databaseId);
await addEntity(
knex,
{
apiVersion: 'a',
kind: 'k',
metadata: { name: 'one' },
spec: {},
relations: [],
},
[],
);
await addEntity(
knex,
{
apiVersion: 'a',
kind: 'k',
metadata: { name: 'two' },
spec: {},
relations: [],
},
[],
);
const catalog = new DefaultEntitiesCatalog(knex, stitcher);
const { items } = await catalog.entitiesBatch({
entityRefs: [
'k:default/two',
'k:default/one',
'k:default/two',
'not-even-a-ref',
'k:default/does-not-exist',
'k:default/two',
],
});
expect(items.map(e => e && stringifyEntityRef(e))).toEqual([
'k:default/two',
'k:default/one',
'k:default/two',
null,
null,
'k:default/two',
]);
},
);
});
describe('removeEntityByUid', () => {
it.each(databases.eachSupportedId())(
'also clears parent hashes',
@@ -23,6 +23,8 @@ import { InputError, NotFoundError } from '@backstage/errors';
import { Knex } from 'knex';
import lodash from 'lodash';
import {
EntitiesBatchRequest,
EntitiesBatchResponse,
EntitiesCatalog,
EntitiesRequest,
EntitiesResponse,
@@ -237,6 +239,38 @@ export class DefaultEntitiesCatalog implements EntitiesCatalog {
};
}
async entitiesBatch(
request: EntitiesBatchRequest,
): Promise<EntitiesBatchResponse> {
const lookup = new Map<string, Entity>();
for (const chunk of lodash.chunk(request.entityRefs, 200)) {
let query = this.database<DbFinalEntitiesRow>('final_entities')
.innerJoin<DbRefreshStateRow>('refresh_state', {
'refresh_state.entity_id': 'final_entities.entity_id',
})
.select({
entityRef: 'refresh_state.entity_ref',
entity: 'final_entities.final_entity',
})
.whereIn('refresh_state.entity_ref', chunk);
if (request?.filter) {
query = parseFilter(request.filter, query, this.database);
}
for (const row of await query) {
lookup.set(row.entityRef, row.entity ? JSON.parse(row.entity) : null);
}
}
let items = request.entityRefs.map(ref => lookup.get(ref) ?? null);
if (request.fields) {
items = items.map(e => e && request.fields!(e));
}
return { items };
}
async removeEntityByUid(uid: string): Promise<void> {
// Clear the hashed state of the immediate parents of the deleted entity.
// This makes sure that when they get reprocessed, their output is written
@@ -48,6 +48,7 @@ describe('createRouter readonly disabled', () => {
beforeAll(async () => {
entitiesCatalog = {
entities: jest.fn(),
entitiesBatch: jest.fn(),
removeEntityByUid: jest.fn(),
entityAncestry: jest.fn(),
facets: jest.fn(),
@@ -257,6 +258,38 @@ describe('createRouter readonly disabled', () => {
});
});
describe('POST /entities/by-refs', () => {
it.each([
'',
'not json',
'[',
'[]',
'{}',
'{"unknown":7}',
'{"entityRefs":7}',
'{"entityRefs":[7]}',
])('properly rejects malformed request body, %p', async p => {
await expect(
request(app)
.post('/entities/by-refs')
.set('Content-Type', 'application/json')
.send(p),
).resolves.toMatchObject({ status: 400 });
});
it('can fetch entities by refs', async () => {
const entity: Entity = {} as any;
entitiesCatalog.entitiesBatch.mockResolvedValue({ items: [entity] });
const response = await request(app)
.post('/entities/by-refs')
.set('Content-Type', 'application/json')
.send('{"entityRefs":["a"]}');
expect(entitiesCatalog.entitiesBatch).toHaveBeenCalledTimes(1);
expect(response.status).toEqual(200);
expect(response.body).toEqual({ items: [entity] });
});
});
describe('GET /locations', () => {
it('happy path: lists locations', async () => {
const locations: Location[] = [
@@ -517,6 +550,7 @@ describe('createRouter readonly enabled', () => {
beforeAll(async () => {
entitiesCatalog = {
entities: jest.fn(),
entitiesBatch: jest.fn(),
removeEntityByUid: jest.fn(),
entityAncestry: jest.fn(),
facets: jest.fn(),
@@ -706,6 +740,7 @@ describe('NextRouter permissioning', () => {
beforeAll(async () => {
entitiesCatalog = {
entities: jest.fn(),
entitiesBatch: jest.fn(),
removeEntityByUid: jest.fn(),
entityAncestry: jest.fn(),
facets: jest.fn(),
@@ -28,24 +28,25 @@ import express from 'express';
import Router from 'express-promise-router';
import { Logger } from 'winston';
import yn from 'yn';
import { z } from 'zod';
import { EntitiesCatalog } from '../catalog/types';
import { LocationAnalyzer } from '../ingestion/types';
import { CatalogProcessingOrchestrator } from '../processing/types';
import { validateEntityEnvelope } from '../processing/util';
import {
basicEntityFilter,
entitiesBatchRequest,
parseEntityFilterParams,
parseEntityPaginationParams,
parseEntityTransformParams,
} from './request';
import { parseEntityFacetParams } from './request/parseEntityFacetParams';
import { LocationService, RefreshOptions, RefreshService } from './types';
import {
disallowReadonlyMode,
locationInput,
validateRequestBody,
} from './util';
import { z } from 'zod';
import { parseEntityFacetParams } from './request/parseEntityFacetParams';
import { RefreshOptions, LocationService, RefreshService } from './types';
import { CatalogProcessingOrchestrator } from '../processing/types';
import { validateEntityEnvelope } from '../processing/util';
/**
* Options used by {@link createRouter}.
@@ -173,6 +174,16 @@ export async function createRouter(
res.status(200).json(response);
},
)
.post('/entities/by-refs', async (req, res) => {
const request = entitiesBatchRequest(req);
const token = getBearerToken(req.header('authorization'));
const response = await entitiesCatalog.entitiesBatch({
entityRefs: request.entityRefs,
fields: parseEntityTransformParams(req.query),
authorizationToken: token,
});
res.status(200).json(response);
})
.get('/entity-facets', async (req, res) => {
const response = await entitiesCatalog.facets({
filter: parseEntityFilterParams(req.query),
@@ -0,0 +1,33 @@
/*
* Copyright 2022 The Backstage Authors
*
* 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 { InputError } from '@backstage/errors';
import { Request } from 'express';
import { z } from 'zod';
const schema = z.object({
entityRefs: z.array(z.string()),
});
export function entitiesBatchRequest(req: Request) {
try {
return schema.parse(req.body);
} catch (error) {
throw new InputError(
`Malformed request body (did you remember to specify an application/json content type?), ${error.message}`,
);
}
}
@@ -14,6 +14,7 @@
* limitations under the License.
*/
export { entitiesBatchRequest } from './entitiesBatchRequest';
export { basicEntityFilter } from './basicEntityFilter';
export { parseEntityFilterParams } from './parseEntityFilterParams';
export { parseEntityPaginationParams } from './parseEntityPaginationParams';
@@ -23,7 +23,7 @@ import {
stringifyLocationRef,
} from '@backstage/catalog-model';
import { createHash } from 'crypto';
import { LocationSpec } from '@backstage/plugin-catalog-node';
import { LocationSpec } from '@backstage/plugin-catalog-common';
export function locationSpecToMetadataName(location: LocationSpec) {
const hash = createHash('sha1')
+5 -1
View File
@@ -1 +1,5 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname);
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname, {
rules: {
'testing-library/prefer-screen-queries': 'error',
},
});
@@ -28,6 +28,7 @@ import {
TestApiProvider,
TestApiRegistry,
} from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { catalogGraphRouteRef } from '../../routes';
@@ -79,15 +80,15 @@ describe('<CatalogGraphCard/>', () => {
relations: [],
}));
const { findByText, findAllByTestId } = await renderInTestApp(wrapper, {
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
'/catalog-graph': catalogGraphRouteRef,
},
});
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(1);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(1);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(1);
});
@@ -97,7 +98,7 @@ describe('<CatalogGraphCard/>', () => {
relations: [],
}));
const { findByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<EntityProvider entity={entity}>
<CatalogGraphCard title="Custom Title" />
@@ -111,7 +112,7 @@ describe('<CatalogGraphCard/>', () => {
},
);
expect(await findByText('Custom Title')).toBeInTheDocument();
expect(await screen.findByText('Custom Title')).toBeInTheDocument();
});
test('renders link to standalone viewer', async () => {
@@ -120,15 +121,15 @@ describe('<CatalogGraphCard/>', () => {
relations: [],
}));
const { findByText, getByText } = await renderInTestApp(wrapper, {
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
'/catalog-graph': catalogGraphRouteRef,
},
});
expect(await findByText('b:d/c')).toBeInTheDocument();
const button = getByText('View graph');
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
const button = screen.getByText('View graph');
expect(button).toBeInTheDocument();
expect(button.closest('a')).toHaveAttribute(
'href',
@@ -137,7 +138,7 @@ describe('<CatalogGraphCard/>', () => {
});
test('renders link to standalone viewer with custom config', async () => {
const { findByText, getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<EntityProvider entity={entity}>
<CatalogGraphCard maxDepth={2} mergeRelations={false} />
@@ -151,8 +152,8 @@ describe('<CatalogGraphCard/>', () => {
},
);
expect(await findByText('b:d/c')).toBeInTheDocument();
const button = getByText('View graph');
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
const button = screen.getByText('View graph');
expect(button).toBeInTheDocument();
expect(button.closest('a')).toHaveAttribute(
'href',
@@ -167,7 +168,7 @@ describe('<CatalogGraphCard/>', () => {
}));
const analyticsSpy = new MockAnalyticsApi();
const { findByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[analyticsApiRef, analyticsSpy]]}>
{wrapper}
</TestApiProvider>,
@@ -179,8 +180,8 @@ describe('<CatalogGraphCard/>', () => {
},
);
expect(await findByText('b:d/c')).toBeInTheDocument();
await userEvent.click(await findByText('b:d/c'));
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
await userEvent.click(await screen.findByText('b:d/c'));
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
@@ -22,6 +22,7 @@ import {
renderInTestApp,
TestApiProvider,
} from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { CatalogGraphPage } from './CatalogGraphPage';
@@ -108,19 +109,16 @@ describe('<CatalogGraphPage/>', () => {
n === 'b:d/e' ? entityE : entityC,
);
const { getByText, findByText, findAllByTestId } = await renderInTestApp(
wrapper,
{
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
);
});
expect(getByText('Catalog Graph')).toBeInTheDocument();
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/e')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(2);
expect(screen.getByText('Catalog Graph')).toBeInTheDocument();
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/e')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(2);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(2);
});
@@ -129,17 +127,17 @@ describe('<CatalogGraphPage/>', () => {
n === 'b:d/e' ? entityE : entityC,
);
const { getByText, queryByText } = await renderInTestApp(wrapper, {
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
});
expect(queryByText('Max Depth')).toBeNull();
expect(screen.queryByText('Max Depth')).toBeNull();
await userEvent.click(getByText('Filters'));
await userEvent.click(screen.getByText('Filters'));
expect(getByText('Max Depth')).toBeInTheDocument();
expect(screen.getByText('Max Depth')).toBeInTheDocument();
});
test('should select other entity', async () => {
@@ -147,20 +145,17 @@ describe('<CatalogGraphPage/>', () => {
n === 'b:d/e' ? entityE : entityC,
);
const { getByText, findByText, findAllByTestId } = await renderInTestApp(
wrapper,
{
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
);
});
expect(await findAllByTestId('node')).toHaveLength(2);
expect(await screen.findAllByTestId('node')).toHaveLength(2);
await userEvent.click(getByText('b:d/e'));
await userEvent.click(screen.getByText('b:d/e'));
expect(await findByText('hasPart')).toBeInTheDocument();
expect(await screen.findByText('hasPart')).toBeInTheDocument();
});
test('should navigate to entity', async () => {
@@ -168,17 +163,17 @@ describe('<CatalogGraphPage/>', () => {
n === 'b:d/e' ? entityE : entityC,
);
const { getByText, findAllByTestId } = await renderInTestApp(wrapper, {
await renderInTestApp(wrapper, {
mountedRoutes: {
'/entity/{kind}/{namespace}/{name}': entityRouteRef,
},
});
expect(await findAllByTestId('node')).toHaveLength(2);
expect(await screen.findAllByTestId('node')).toHaveLength(2);
const user = userEvent.setup();
await user.keyboard('{Shift>}');
await user.click(getByText('b:d/e'));
await user.click(screen.getByText('b:d/e'));
expect(navigate).toHaveBeenCalledWith('/entity/{kind}/{namespace}/{name}');
});
@@ -188,7 +183,7 @@ describe('<CatalogGraphPage/>', () => {
);
const analyticsSpy = new MockAnalyticsApi();
const { getByText, findAllByTestId } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[analyticsApiRef, analyticsSpy]]}>
{wrapper}
</TestApiProvider>,
@@ -199,12 +194,12 @@ describe('<CatalogGraphPage/>', () => {
},
);
expect(await findAllByTestId('node')).toHaveLength(2);
expect(await screen.findAllByTestId('node')).toHaveLength(2);
// We wait a bit here to reliably reproduce an issue where that requires the `baseVal` and `view` mocks
await new Promise(r => setTimeout(r, 100));
await userEvent.click(getByText('b:d/e'));
await userEvent.click(screen.getByText('b:d/e'));
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
@@ -218,7 +213,7 @@ describe('<CatalogGraphPage/>', () => {
);
const analyticsSpy = new MockAnalyticsApi();
const { getByText, findAllByTestId } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[analyticsApiRef, analyticsSpy]]}>
{wrapper}
</TestApiProvider>,
@@ -229,11 +224,11 @@ describe('<CatalogGraphPage/>', () => {
},
);
expect(await findAllByTestId('node')).toHaveLength(2);
expect(await screen.findAllByTestId('node')).toHaveLength(2);
const user = userEvent.setup();
await user.keyboard('{Shift>}');
await user.click(getByText('b:d/e'));
await user.click(screen.getByText('b:d/e'));
expect(analyticsSpy.getEvents()[0]).toMatchObject({
action: 'click',
@@ -13,7 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, waitFor } from '@testing-library/react';
import { render, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { CurveFilter } from './CurveFilter';
@@ -21,26 +22,22 @@ import { CurveFilter } from './CurveFilter';
describe('<CurveFilter/>', () => {
test('should display current curve label', () => {
const onChange = jest.fn();
const { getByText } = render(
<CurveFilter value="curveMonotoneX" onChange={onChange} />,
);
render(<CurveFilter value="curveMonotoneX" onChange={onChange} />);
expect(getByText('Monotone X')).toBeInTheDocument();
expect(screen.getByText('Monotone X')).toBeInTheDocument();
});
test('should select an alternative curve factory', async () => {
const onChange = jest.fn();
const { getByText, getByTestId } = render(
<CurveFilter value="curveStepBefore" onChange={onChange} />,
);
render(<CurveFilter value="curveStepBefore" onChange={onChange} />);
expect(getByText('Step Before')).toBeInTheDocument();
expect(screen.getByText('Step Before')).toBeInTheDocument();
await userEvent.click(getByTestId('select'));
await userEvent.click(getByText('Monotone X'));
await userEvent.click(screen.getByTestId('select'));
await userEvent.click(screen.getByText('Monotone X'));
await waitFor(() => {
expect(getByText('Monotone X')).toBeInTheDocument();
expect(screen.getByText('Monotone X')).toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith('curveMonotoneX');
});
});
@@ -13,7 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, waitFor } from '@testing-library/react';
import { render, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { Direction } from '../EntityRelationsGraph';
@@ -21,26 +22,26 @@ import { DirectionFilter } from './DirectionFilter';
describe('<DirectionFilter/>', () => {
test('should display current value', () => {
const { getByText } = render(
render(
<DirectionFilter value={Direction.LEFT_RIGHT} onChange={() => {}} />,
);
expect(getByText('Left to right')).toBeInTheDocument();
expect(screen.getByText('Left to right')).toBeInTheDocument();
});
test('should select direction', async () => {
const onChange = jest.fn();
const { getByText, getByTestId } = render(
render(
<DirectionFilter value={Direction.RIGHT_LEFT} onChange={onChange} />,
);
expect(getByText('Right to left')).toBeInTheDocument();
expect(screen.getByText('Right to left')).toBeInTheDocument();
await userEvent.click(getByTestId('select'));
await userEvent.click(getByText('Top to bottom'));
await userEvent.click(screen.getByTestId('select'));
await userEvent.click(screen.getByText('Top to bottom'));
await waitFor(() => {
expect(getByText('Top to bottom')).toBeInTheDocument();
expect(screen.getByText('Top to bottom')).toBeInTheDocument();
expect(onChange).toHaveBeenCalledWith(Direction.TOP_BOTTOM);
});
});
@@ -13,64 +13,65 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { MaxDepthFilter } from './MaxDepthFilter';
describe('<MaxDepthFilter/>', () => {
test('should display current value', () => {
const { getByLabelText } = render(
<MaxDepthFilter value={5} onChange={() => {}} />,
);
render(<MaxDepthFilter value={5} onChange={() => {}} />);
expect(getByLabelText('maxp')).toBeInTheDocument();
expect(getByLabelText('maxp')).toHaveValue(5);
expect(screen.getByLabelText('maxp')).toBeInTheDocument();
expect(screen.getByLabelText('maxp')).toHaveValue(5);
});
test('should display infinite if non finite', () => {
const { getByPlaceholderText, getByLabelText } = render(
render(
<MaxDepthFilter value={Number.POSITIVE_INFINITY} onChange={() => {}} />,
);
expect(getByPlaceholderText(/Infinite/)).toBeInTheDocument();
expect(getByLabelText('maxp')).toHaveValue(null);
expect(screen.getByPlaceholderText(/Infinite/)).toBeInTheDocument();
expect(screen.getByLabelText('maxp')).toHaveValue(null);
});
test('should clear max depth', async () => {
const onChange = jest.fn();
const { getByLabelText } = render(
<MaxDepthFilter value={10} onChange={onChange} />,
);
render(<MaxDepthFilter value={10} onChange={onChange} />);
await userEvent.click(getByLabelText('clear max depth'));
expect(onChange).not.toHaveBeenCalled();
await user.click(screen.getByLabelText('clear max depth'));
expect(onChange).toHaveBeenCalledWith(Number.POSITIVE_INFINITY);
});
test('should set max depth to undefined if below one', async () => {
const onChange = jest.fn();
const { getByLabelText } = render(
<MaxDepthFilter value={1} onChange={onChange} />,
);
render(<MaxDepthFilter value={1} onChange={onChange} />);
await userEvent.clear(getByLabelText('maxp'));
await userEvent.type(getByLabelText('maxp'), '0');
await user.clear(screen.getByLabelText('maxp'));
await user.type(screen.getByLabelText('maxp'), '0');
expect(onChange).toHaveBeenCalledWith(Number.POSITIVE_INFINITY);
});
test('should select direction', async () => {
const onChange = jest.fn();
const { getByLabelText } = render(
<MaxDepthFilter value={5} onChange={onChange} />,
let value = 5;
render(
<MaxDepthFilter
value={value}
onChange={v => {
value = v;
}}
/>,
);
expect(getByLabelText('maxp')).toHaveValue(5);
expect(screen.getByLabelText('maxp')).toHaveValue(5);
expect(value).toBe(5);
await userEvent.clear(getByLabelText('maxp'));
await userEvent.type(getByLabelText('maxp'), '10');
waitFor(() => {
expect(onChange).toHaveBeenCalledWith(10);
});
await user.clear(screen.getByLabelText('maxp'));
expect(value).toBe(Number.POSITIVE_INFINITY);
await user.type(screen.getByLabelText('maxp'), '10');
expect(value).toBe(10);
});
});
@@ -23,7 +23,7 @@ import {
Typography,
} from '@material-ui/core';
import ClearIcon from '@material-ui/icons/Clear';
import React, { useCallback } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
export type Props = {
value: number;
@@ -42,18 +42,37 @@ const useStyles = makeStyles(
export const MaxDepthFilter = ({ value, onChange }: Props) => {
const classes = useStyles();
const onChangeRef = useRef(onChange);
const [currentValue, setCurrentValue] = useState(value);
// Keep a fresh reference to the latest callback
useEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);
// If the value changes externally, update ourselves
useEffect(() => {
setCurrentValue(value);
}, [value]);
// When the entered text changes, update ourselves and communicate externally
const handleChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const v = Number(event.target.value);
onChange(v <= 0 ? Number.POSITIVE_INFINITY : v);
const newValueNumeric = Number(event.target.value);
const newValue =
Number.isFinite(newValueNumeric) && newValueNumeric > 0
? newValueNumeric
: Number.POSITIVE_INFINITY;
setCurrentValue(newValue);
onChangeRef.current(newValue);
},
[onChange],
[],
);
const reset = useCallback(() => {
onChange(Number.POSITIVE_INFINITY);
}, [onChange]);
setCurrentValue(Number.POSITIVE_INFINITY);
onChangeRef.current(Number.POSITIVE_INFINITY);
}, [onChangeRef]);
return (
<Box pb={1} pt={1}>
@@ -62,7 +81,7 @@ export const MaxDepthFilter = ({ value, onChange }: Props) => {
<OutlinedInput
type="number"
placeholder="∞ Infinite"
value={isFinite(value) ? value : ''}
value={Number.isFinite(currentValue) ? String(currentValue) : ''}
onChange={handleChange}
endAdornment={
<InputAdornment position="end">
@@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { GetEntityFacetsResponse } from '@backstage/catalog-client';
import { ApiProvider } from '@backstage/core-app-api';
import { AlertApi, alertApiRef } from '@backstage/core-plugin-api';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { renderWithEffects, TestApiRegistry } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { SelectedKindsFilter } from './SelectedKindsFilter';
@@ -42,37 +43,37 @@ const apis = TestApiRegistry.from(
describe('<SelectedKindsFilter/>', () => {
it('should not explode while loading', async () => {
const rendered = await renderWithEffects(
const { baseElement } = await renderWithEffects(
<ApiProvider apis={apis}>
<SelectedKindsFilter value={['api', 'component']} onChange={() => {}} />
</ApiProvider>,
);
expect(rendered.baseElement).toBeInTheDocument();
expect(baseElement).toBeInTheDocument();
});
it('should render current value', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<SelectedKindsFilter value={['api', 'component']} onChange={() => {}} />
</ApiProvider>,
);
expect(rendered.getByText('API')).toBeInTheDocument();
expect(rendered.getByText('Component')).toBeInTheDocument();
expect(screen.getByText('API')).toBeInTheDocument();
expect(screen.getByText('Component')).toBeInTheDocument();
});
it('should select value', async () => {
const onChange = jest.fn();
const { getByLabelText, getByText } = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<SelectedKindsFilter value={['api', 'component']} onChange={onChange} />
</ApiProvider>,
);
await userEvent.click(getByLabelText('Open'));
await waitFor(() => expect(getByText('System')).toBeInTheDocument());
await userEvent.click(screen.getByLabelText('Open'));
await waitFor(() => expect(screen.getByText('System')).toBeInTheDocument());
await userEvent.click(getByText('System'));
await userEvent.click(screen.getByText('System'));
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(['api', 'component', 'system']);
@@ -81,7 +82,7 @@ describe('<SelectedKindsFilter/>', () => {
it('should return undefined if all values are selected', async () => {
const onChange = jest.fn();
const { getByLabelText, getByText } = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<SelectedKindsFilter
value={['api', 'component', 'system', 'domain']}
@@ -89,11 +90,13 @@ describe('<SelectedKindsFilter/>', () => {
/>
</ApiProvider>,
);
await userEvent.click(getByLabelText('Open'));
await userEvent.click(screen.getByLabelText('Open'));
await waitFor(() => expect(getByText('Resource')).toBeInTheDocument());
await waitFor(() =>
expect(screen.getByText('Resource')).toBeInTheDocument(),
);
await userEvent.click(getByText('Resource'));
await userEvent.click(screen.getByText('Resource'));
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(undefined);
@@ -102,13 +105,13 @@ describe('<SelectedKindsFilter/>', () => {
it('should return all values when cleared', async () => {
const onChange = jest.fn();
const { getByRole } = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<SelectedKindsFilter value={[]} onChange={onChange} />
</ApiProvider>,
);
await userEvent.click(getByRole('combobox'));
await userEvent.click(screen.getByRole('combobox'));
await userEvent.tab();
await waitFor(() => {
@@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
RELATION_CHILD_OF,
RELATION_HAS_MEMBER,
RELATION_OWNED_BY,
} from '@backstage/catalog-model';
import { render, waitFor } from '@testing-library/react';
import { render, waitFor, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { ALL_RELATION_PAIRS } from '../EntityRelationsGraph';
@@ -26,7 +27,7 @@ import { SelectedRelationsFilter } from './SelectedRelationsFilter';
describe('<SelectedRelationsFilter/>', () => {
test('should render current value', () => {
const { getByText } = render(
render(
<SelectedRelationsFilter
relationPairs={ALL_RELATION_PAIRS}
value={[RELATION_OWNED_BY, RELATION_CHILD_OF]}
@@ -34,13 +35,13 @@ describe('<SelectedRelationsFilter/>', () => {
/>,
);
expect(getByText(RELATION_OWNED_BY)).toBeInTheDocument();
expect(getByText(RELATION_CHILD_OF)).toBeInTheDocument();
expect(screen.getByText(RELATION_OWNED_BY)).toBeInTheDocument();
expect(screen.getByText(RELATION_CHILD_OF)).toBeInTheDocument();
});
test('should select value', async () => {
const onChange = jest.fn();
const { getByText, getByLabelText } = render(
render(
<SelectedRelationsFilter
relationPairs={ALL_RELATION_PAIRS}
value={[RELATION_OWNED_BY, RELATION_CHILD_OF]}
@@ -48,13 +49,13 @@ describe('<SelectedRelationsFilter/>', () => {
/>,
);
await userEvent.click(getByLabelText('Open'));
await userEvent.click(screen.getByLabelText('Open'));
await waitFor(() =>
expect(getByText(RELATION_HAS_MEMBER)).toBeInTheDocument(),
expect(screen.getByText(RELATION_HAS_MEMBER)).toBeInTheDocument(),
);
await userEvent.click(getByText(RELATION_HAS_MEMBER));
await userEvent.click(screen.getByText(RELATION_HAS_MEMBER));
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith([
@@ -67,7 +68,7 @@ describe('<SelectedRelationsFilter/>', () => {
test('should return undefined if all values are selected', async () => {
const onChange = jest.fn();
const { getByText, getByLabelText } = render(
render(
<SelectedRelationsFilter
relationPairs={ALL_RELATION_PAIRS}
value={ALL_RELATION_PAIRS.flatMap(p => p).filter(
@@ -77,13 +78,13 @@ describe('<SelectedRelationsFilter/>', () => {
/>,
);
await userEvent.click(getByLabelText('Open'));
await userEvent.click(screen.getByLabelText('Open'));
await waitFor(() =>
expect(getByText(RELATION_HAS_MEMBER)).toBeInTheDocument(),
expect(screen.getByText(RELATION_HAS_MEMBER)).toBeInTheDocument(),
);
await userEvent.click(getByText(RELATION_HAS_MEMBER));
await userEvent.click(screen.getByText(RELATION_HAS_MEMBER));
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith(undefined);
@@ -92,7 +93,7 @@ describe('<SelectedRelationsFilter/>', () => {
test('should return all values when cleared', async () => {
const onChange = jest.fn();
const { getByRole } = render(
render(
<SelectedRelationsFilter
relationPairs={ALL_RELATION_PAIRS}
value={[]}
@@ -100,7 +101,7 @@ describe('<SelectedRelationsFilter/>', () => {
/>,
);
await userEvent.click(getByRole('combobox'));
await userEvent.click(screen.getByRole('combobox'));
await userEvent.tab();
await waitFor(() => {
@@ -13,31 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { SwitchFilter } from './SwitchFilter';
describe('<SwitchFilter/>', () => {
test('should render value', () => {
const { getByLabelText } = render(
<SwitchFilter label="My label" value={false} onChange={() => {}} />,
);
render(<SwitchFilter label="My label" value={false} onChange={() => {}} />);
expect(getByLabelText('My label')).toBeInTheDocument();
expect(getByLabelText('My label')).not.toBeChecked();
expect(screen.getByLabelText('My label')).toBeInTheDocument();
expect(screen.getByLabelText('My label')).not.toBeChecked();
});
test('should toggle value', async () => {
const onChange = jest.fn();
const { getByLabelText } = render(
<SwitchFilter label="My label" value onChange={onChange} />,
);
render(<SwitchFilter label="My label" value onChange={onChange} />);
expect(getByLabelText('My label')).toBeInTheDocument();
expect(getByLabelText('My label')).toBeChecked();
expect(screen.getByLabelText('My label')).toBeInTheDocument();
expect(screen.getByLabelText('My label')).toBeChecked();
await userEvent.click(getByLabelText('My label'));
await userEvent.click(screen.getByLabelText('My label'));
expect(onChange).toHaveBeenCalledWith(false);
});
@@ -13,17 +13,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
RELATION_CHILD_OF,
RELATION_PARENT_OF,
} from '@backstage/catalog-model';
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import React from 'react';
import { CustomLabel } from './CustomLabel';
describe('<CustomLabel />', () => {
test('renders label', () => {
const { getByText } = render(
render(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomLabel
edge={{
@@ -36,11 +37,11 @@ describe('<CustomLabel />', () => {
</svg>,
);
expect(getByText(RELATION_PARENT_OF)).toBeInTheDocument();
expect(screen.getByText(RELATION_PARENT_OF)).toBeInTheDocument();
});
test('renders label with multiple relations', () => {
const { getByText } = render(
render(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomLabel
edge={{
@@ -53,7 +54,7 @@ describe('<CustomLabel />', () => {
</svg>,
);
expect(getByText(RELATION_PARENT_OF)).toBeInTheDocument();
expect(getByText(RELATION_CHILD_OF)).toBeInTheDocument();
expect(screen.getByText(RELATION_PARENT_OF)).toBeInTheDocument();
expect(screen.getByText(RELATION_CHILD_OF)).toBeInTheDocument();
});
});
@@ -13,14 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { CustomNode } from './CustomNode';
import userEvent from '@testing-library/user-event';
describe('<CustomNode />', () => {
test('renders node', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomNode
node={{
@@ -35,11 +37,11 @@ describe('<CustomNode />', () => {
</svg>,
);
expect(getByText('kind:namespace/name')).toBeInTheDocument();
expect(screen.getByText('kind:namespace/name')).toBeInTheDocument();
});
test('renders node, skips default namespace', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomNode
node={{
@@ -53,12 +55,12 @@ describe('<CustomNode />', () => {
</svg>,
);
expect(getByText('kind:name')).toBeInTheDocument();
expect(screen.getByText('kind:name')).toBeInTheDocument();
});
test('renders node with onClick', async () => {
const onClick = jest.fn();
const { getByText } = await renderInTestApp(
await renderInTestApp(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomNode
node={{
@@ -73,13 +75,13 @@ describe('<CustomNode />', () => {
</svg>,
);
expect(getByText('kind:namespace/name')).toBeInTheDocument();
await userEvent.click(getByText('kind:namespace/name'));
expect(screen.getByText('kind:namespace/name')).toBeInTheDocument();
await userEvent.click(screen.getByText('kind:namespace/name'));
expect(onClick).toHaveBeenCalledTimes(1);
});
test('renders title if entity has one', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<svg xmlns="http://www.w3.org/2000/svg">
<CustomNode
node={{
@@ -94,6 +96,6 @@ describe('<CustomNode />', () => {
</svg>,
);
expect(getByText('Custom Title')).toBeInTheDocument();
expect(screen.getByText('Custom Title')).toBeInTheDocument();
});
});
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { renderInTestApp } from '@backstage/test-utils';
import React from 'react';
import { EntityKindIcon } from './EntityKindIcon';
@@ -24,6 +24,7 @@ import {
import { DependencyGraphTypes } from '@backstage/core-components';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React, { FunctionComponent } from 'react';
import { EntityRelationsGraph } from './EntityRelationsGraph';
@@ -142,7 +143,7 @@ describe('<EntityRelationsGraph/>', () => {
relations: [],
});
const { findByText, findAllByTestId } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -150,15 +151,15 @@ describe('<EntityRelationsGraph/>', () => {
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(1);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(1);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(1);
});
test('renders a progress indicator while loading', async () => {
catalog.getEntityByRef.mockImplementation(() => new Promise(() => {}));
const { findByRole } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -166,7 +167,7 @@ describe('<EntityRelationsGraph/>', () => {
</Wrapper>,
);
expect(await findByRole('progressbar')).toBeInTheDocument();
expect(await screen.findByRole('progressbar')).toBeInTheDocument();
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(1);
});
@@ -197,7 +198,7 @@ describe('<EntityRelationsGraph/>', () => {
return undefined;
});
const { findByText, findAllByTestId } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -205,32 +206,31 @@ describe('<EntityRelationsGraph/>', () => {
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(1);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(1);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(2);
});
test('renders at max depth of one', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findByText, findAllByTestId, findAllByText } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
maxDepth={1}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
maxDepth={1}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/c1')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(3);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/c1')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(3);
expect(await findAllByText('ownerOf')).toHaveLength(1);
expect(await findAllByText('hasPart')).toHaveLength(1);
expect(await findAllByTestId('label')).toHaveLength(2);
expect(await screen.findAllByText('ownerOf')).toHaveLength(1);
expect(await screen.findAllByText('hasPart')).toHaveLength(1);
expect(await screen.findAllByTestId('label')).toHaveLength(2);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(3);
});
@@ -238,26 +238,25 @@ describe('<EntityRelationsGraph/>', () => {
test('renders simplified graph at full depth', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findByText, findAllByText, findAllByTestId } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional
maxDepth={Number.POSITIVE_INFINITY}
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional
maxDepth={Number.POSITIVE_INFINITY}
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/c1')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findByText('b:d/c2')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(4);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/c1')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findByText('b:d/c2')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(4);
expect(await findAllByText('ownerOf')).toHaveLength(1);
expect(await findAllByText('hasPart')).toHaveLength(2);
expect(await findAllByTestId('label')).toHaveLength(3);
expect(await screen.findAllByText('ownerOf')).toHaveLength(1);
expect(await screen.findAllByText('hasPart')).toHaveLength(2);
expect(await screen.findAllByTestId('label')).toHaveLength(3);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(4);
});
@@ -265,28 +264,27 @@ describe('<EntityRelationsGraph/>', () => {
test('renders full graph at full depth', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findAllByText, findByText, findAllByTestId } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional={false}
mergeRelations={false}
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional={false}
mergeRelations={false}
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/c1')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findByText('b:d/c2')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(4);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/c1')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findByText('b:d/c2')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(4);
expect(await findAllByText('ownerOf')).toHaveLength(2);
expect(await findAllByText('ownedBy')).toHaveLength(2);
expect(await findAllByText('hasPart')).toHaveLength(2);
expect(await findAllByText('partOf')).toHaveLength(2);
expect(await findAllByTestId('label')).toHaveLength(8);
expect(await screen.findAllByText('ownerOf')).toHaveLength(2);
expect(await screen.findAllByText('ownedBy')).toHaveLength(2);
expect(await screen.findAllByText('hasPart')).toHaveLength(2);
expect(await screen.findAllByText('partOf')).toHaveLength(2);
expect(await screen.findAllByTestId('label')).toHaveLength(8);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(4);
});
@@ -294,26 +292,25 @@ describe('<EntityRelationsGraph/>', () => {
test('renders full graph at full depth with merged relations', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findAllByText, findByText, findAllByTestId } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional={false}
mergeRelations
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
unidirectional={false}
mergeRelations
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/c1')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findByText('b:d/c2')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(4);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/c1')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findByText('b:d/c2')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(4);
expect(await findAllByText('ownerOf')).toHaveLength(2);
expect(await findAllByText('hasPart')).toHaveLength(2);
expect(await findAllByTestId('label')).toHaveLength(4);
expect(await screen.findAllByText('ownerOf')).toHaveLength(2);
expect(await screen.findAllByText('hasPart')).toHaveLength(2);
expect(await screen.findAllByTestId('label')).toHaveLength(4);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(4);
});
@@ -321,27 +318,26 @@ describe('<EntityRelationsGraph/>', () => {
test('renders a graph with multiple root nodes', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findAllByText, findByText, findAllByTestId } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={[
{ kind: 'b', namespace: 'd', name: 'c' },
{ kind: 'b', namespace: 'd', name: 'c2' },
]}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={[
{ kind: 'b', namespace: 'd', name: 'c' },
{ kind: 'b', namespace: 'd', name: 'c2' },
]}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('b:d/c1')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findByText('b:d/c2')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(4);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('b:d/c1')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findByText('b:d/c2')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(4);
expect(await findAllByText('ownerOf')).toHaveLength(1);
expect(await findAllByText('partOf')).toHaveLength(2);
expect(await findAllByTestId('label')).toHaveLength(3);
expect(await screen.findAllByText('ownerOf')).toHaveLength(1);
expect(await screen.findAllByText('partOf')).toHaveLength(2);
expect(await screen.findAllByTestId('label')).toHaveLength(3);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(4);
});
@@ -349,23 +345,22 @@ describe('<EntityRelationsGraph/>', () => {
test('renders a graph with filtered kinds and relations', async () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const { findAllByText, findByText, findAllByTestId } =
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
relations={['ownerOf', 'ownedBy']}
kinds={['k']}
/>
</Wrapper>,
);
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
relations={['ownerOf', 'ownedBy']}
kinds={['k']}
/>
</Wrapper>,
);
expect(await findByText('b:d/c')).toBeInTheDocument();
expect(await findByText('k:d/a1')).toBeInTheDocument();
expect(await findAllByTestId('node')).toHaveLength(2);
expect(await screen.findByText('b:d/c')).toBeInTheDocument();
expect(await screen.findByText('k:d/a1')).toBeInTheDocument();
expect(await screen.findAllByTestId('node')).toHaveLength(2);
expect(await findAllByText('ownerOf')).toHaveLength(1);
expect(await findAllByTestId('label')).toHaveLength(1);
expect(await screen.findAllByText('ownerOf')).toHaveLength(1);
expect(await screen.findAllByTestId('label')).toHaveLength(1);
expect(catalog.getEntityByRef).toHaveBeenCalledTimes(2);
});
@@ -374,7 +369,7 @@ describe('<EntityRelationsGraph/>', () => {
catalog.getEntityByRef.mockImplementation(async n => entities[n as string]);
const onNodeClick = jest.fn();
const { findByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -383,7 +378,7 @@ describe('<EntityRelationsGraph/>', () => {
</Wrapper>,
);
await userEvent.click(await findByText('k:d/a1'));
await userEvent.click(await screen.findByText('k:d/a1'));
expect(onNodeClick).toHaveBeenCalledTimes(1);
});
@@ -397,7 +392,7 @@ describe('<EntityRelationsGraph/>', () => {
</g>
);
const { findAllByTestId, container } = await renderInTestApp(
const { container } = await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -406,7 +401,7 @@ describe('<EntityRelationsGraph/>', () => {
</Wrapper>,
);
const node = await findAllByTestId(CUSTOM_TEST_ID);
const node = await screen.findAllByTestId(CUSTOM_TEST_ID);
expect(node[0]).toBeInTheDocument();
expect(container.querySelector('circle')).toBeInTheDocument();
});
@@ -421,7 +416,7 @@ describe('<EntityRelationsGraph/>', () => {
</g>
);
const { findAllByTestId, findAllByText, container } = await renderInTestApp(
const { container } = await renderInTestApp(
<Wrapper>
<EntityRelationsGraph
rootEntityNames={{ kind: 'b', namespace: 'd', name: 'c' }}
@@ -429,10 +424,10 @@ describe('<EntityRelationsGraph/>', () => {
/>
</Wrapper>,
);
const node = await findAllByTestId(CUSTOM_TEST_ID);
const node = await screen.findAllByTestId(CUSTOM_TEST_ID);
expect(node[0]).toBeInTheDocument();
expect(container.querySelector('circle')).toBeInTheDocument();
const labels = await findAllByText('Test-Labelvisible');
const labels = await screen.findAllByText('Test-Labelvisible');
expect(labels[0]).toBeInTheDocument();
});
});
+5 -1
View File
@@ -1 +1,5 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname);
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname, {
rules: {
'testing-library/prefer-screen-queries': 'error',
},
});
@@ -19,6 +19,7 @@ import { ApiProvider, ConfigReader } from '@backstage/core-app-api';
import { configApiRef } from '@backstage/core-plugin-api';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiRegistry } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { catalogImportApiRef, CatalogImportClient } from '../../api';
import { DefaultImportPage } from './DefaultImportPage';
@@ -65,14 +66,14 @@ describe('<DefaultImportPage />', () => {
});
it('renders without exploding', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<DefaultImportPage />
</ApiProvider>,
);
expect(
getByText('Start tracking your component in Backstage'),
screen.getByText('Start tracking your component in Backstage'),
).toBeInTheDocument();
});
});
@@ -21,6 +21,7 @@ import {
TestApiProvider,
TestApiRegistry,
} from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { CatalogImportApi, catalogImportApiRef } from '../../api';
import { ImportInfoCard } from './ImportInfoCard';
@@ -49,7 +50,7 @@ describe('<ImportInfoCard />', () => {
});
it('renders without exploding', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[configApiRef, new ConfigReader({ integrations: {} })],
@@ -60,32 +61,34 @@ describe('<ImportInfoCard />', () => {
</TestApiProvider>,
);
expect(getByText('Register an existing component')).toBeInTheDocument();
expect(
screen.getByText('Register an existing component'),
).toBeInTheDocument();
});
it('renders section on GitHub discovery if supported', async () => {
catalogImportApi.preparePullRequest = async () => ({ title: '', body: '' });
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<ImportInfoCard />
</ApiProvider>,
);
expect(getByText(/The wizard discovers all/)).toBeInTheDocument();
expect(screen.getByText(/The wizard discovers all/)).toBeInTheDocument();
});
it('renders section on pull requests if supported', async () => {
catalogImportApi.preparePullRequest = async () => ({ title: '', body: '' });
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<ImportInfoCard />
</ApiProvider>,
);
expect(
getByText(/the wizard will prepare a Pull Request/),
screen.getByText(/the wizard will prepare a Pull Request/),
).toBeInTheDocument();
});
});
@@ -19,6 +19,7 @@ import { ApiProvider, ConfigReader } from '@backstage/core-app-api';
import { configApiRef } from '@backstage/core-plugin-api';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiRegistry } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { useOutlet } from 'react-router';
import { catalogImportApiRef, CatalogImportClient } from '../../api';
@@ -71,26 +72,26 @@ describe('<ImportPage />', () => {
afterEach(() => jest.resetAllMocks());
it('renders without exploding', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<ImportPage />
</ApiProvider>,
);
expect(
getByText('Start tracking your component in Backstage'),
screen.getByText('Start tracking your component in Backstage'),
).toBeInTheDocument();
});
it('renders with custom children', async () => {
(useOutlet as jest.Mock).mockReturnValue(<div>Hello World</div>);
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<ImportPage />
</ApiProvider>,
);
expect(getByText('Hello World')).toBeInTheDocument();
expect(screen.getByText('Hello World')).toBeInTheDocument();
});
});
@@ -16,7 +16,7 @@
import { errorApiRef } from '@backstage/core-plugin-api';
import { TestApiProvider } from '@backstage/test-utils';
import { act, render } from '@testing-library/react';
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { AnalyzeResult, catalogImportApiRef } from '../../api/';
@@ -60,19 +60,20 @@ describe('<StepInitAnalyzeUrl />', () => {
});
it('renders without exploding', async () => {
const { getByRole } = render(
<StepInitAnalyzeUrl onAnalysis={() => undefined} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={() => undefined} />, {
wrapper: Wrapper,
});
expect(getByRole('textbox', { name: /Repository/i })).toBeInTheDocument();
expect(getByRole('textbox', { name: /Repository/i })).toHaveValue('');
expect(
screen.getByRole('textbox', { name: /Repository/i }),
).toBeInTheDocument();
expect(screen.getByRole('textbox', { name: /Repository/i })).toHaveValue(
'',
);
});
it('should use default analysis url', async () => {
const { getByRole } = render(
render(
<StepInitAnalyzeUrl
onAnalysis={() => undefined}
analysisUrl="https://default"
@@ -82,8 +83,10 @@ describe('<StepInitAnalyzeUrl />', () => {
},
);
expect(getByRole('textbox', { name: /Repository/i })).toBeInTheDocument();
expect(getByRole('textbox', { name: /Repository/i })).toHaveValue(
expect(
screen.getByRole('textbox', { name: /Repository/i }),
).toBeInTheDocument();
expect(screen.getByRole('textbox', { name: /Repository/i })).toHaveValue(
'https://default',
);
});
@@ -91,16 +94,13 @@ describe('<StepInitAnalyzeUrl />', () => {
it('should not analyze without url', async () => {
const onAnalysisFn = jest.fn();
const { getByRole } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
await act(async () => {
try {
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
} catch {
return;
}
@@ -114,26 +114,23 @@ describe('<StepInitAnalyzeUrl />', () => {
it('should not analyze invalid value', async () => {
const onAnalysisFn = jest.fn();
const { getByRole, getByText } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'http:/',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(catalogImportApi.analyzeUrl).toHaveBeenCalledTimes(0);
expect(onAnalysisFn).toHaveBeenCalledTimes(0);
expect(errorApi.post).toHaveBeenCalledTimes(0);
expect(
getByText('Must start with http:// or https://.'),
screen.getByText('Must start with http:// or https://.'),
).toBeInTheDocument();
});
@@ -145,12 +142,9 @@ describe('<StepInitAnalyzeUrl />', () => {
locations: [location],
} as AnalyzeResult;
const { getByRole } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve(analyzeResult),
@@ -158,10 +152,10 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(1);
@@ -182,12 +176,9 @@ describe('<StepInitAnalyzeUrl />', () => {
locations: [location, location],
} as AnalyzeResult;
const { getByRole } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve(analyzeResult),
@@ -195,10 +186,10 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-1',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(1);
@@ -218,12 +209,9 @@ describe('<StepInitAnalyzeUrl />', () => {
locations: [],
} as AnalyzeResult;
const { getByRole, getByText } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve(analyzeResult),
@@ -231,15 +219,15 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-1',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(0);
expect(
getByText('There are no entities at this location'),
screen.getByText('There are no entities at this location'),
).toBeInTheDocument();
expect(errorApi.post).toHaveBeenCalledTimes(0);
});
@@ -262,12 +250,9 @@ describe('<StepInitAnalyzeUrl />', () => {
],
} as AnalyzeResult;
const { getByRole } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve(analyzeResult),
@@ -275,10 +260,10 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-2',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(1);
@@ -300,12 +285,9 @@ describe('<StepInitAnalyzeUrl />', () => {
generatedEntities: [],
} as AnalyzeResult;
const { getByRole, getByText } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve(analyzeResult),
@@ -313,15 +295,15 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-2',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(0);
expect(
getByText("Couldn't generate entities for your repository"),
screen.getByText("Couldn't generate entities for your repository"),
).toBeInTheDocument();
expect(errorApi.post).toHaveBeenCalledTimes(0);
});
@@ -344,7 +326,7 @@ describe('<StepInitAnalyzeUrl />', () => {
],
} as AnalyzeResult;
const { getByRole, getByText } = render(
render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} disablePullRequest />,
{
wrapper: Wrapper,
@@ -357,15 +339,15 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-2',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(0);
expect(
getByText("Couldn't generate entities for your repository"),
screen.getByText("Couldn't generate entities for your repository"),
).toBeInTheDocument();
expect(errorApi.post).toHaveBeenCalledTimes(0);
});
@@ -373,12 +355,9 @@ describe('<StepInitAnalyzeUrl />', () => {
it('should report unknown type to the errorapi', async () => {
const onAnalysisFn = jest.fn();
const { getByRole, getByText } = render(
<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />,
{
wrapper: Wrapper,
},
);
render(<StepInitAnalyzeUrl onAnalysis={onAnalysisFn} />, {
wrapper: Wrapper,
});
catalogImportApi.analyzeUrl.mockReturnValueOnce(
Promise.resolve({ type: 'unknown' } as any as AnalyzeResult),
@@ -386,15 +365,15 @@ describe('<StepInitAnalyzeUrl />', () => {
await act(async () => {
await userEvent.type(
getByRole('textbox', { name: /Repository/i }),
screen.getByRole('textbox', { name: /Repository/i }),
'https://my-repository-2',
);
await userEvent.click(getByRole('button', { name: /Analyze/i }));
await userEvent.click(screen.getByRole('button', { name: /Analyze/i }));
});
expect(onAnalysisFn).toHaveBeenCalledTimes(0);
expect(
getByText(
screen.getByText(
'Received unknown analysis result of type unknown. Please contact the support team.',
),
).toBeInTheDocument();
@@ -15,7 +15,7 @@
*/
import { FormHelperText, TextField } from '@material-ui/core';
import { act, render } from '@testing-library/react';
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { asInputRef } from '../helpers';
@@ -25,7 +25,7 @@ describe('<PreparePullRequestForm />', () => {
it('renders without exploding', async () => {
const onSubmitFn = jest.fn();
const { getByRole } = render(
render(
<PreparePullRequestForm<{ main: string }>
defaultValues={{ main: 'default' }}
render={({ register }) => (
@@ -39,7 +39,7 @@ describe('<PreparePullRequestForm />', () => {
);
await act(async () => {
await userEvent.click(getByRole('button', { name: /submit/i }));
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
});
expect(onSubmitFn).toHaveBeenCalledTimes(1);
@@ -49,7 +49,7 @@ describe('<PreparePullRequestForm />', () => {
it('should register a text field', async () => {
const onSubmitFn = jest.fn();
const { getByRole, getByLabelText } = render(
render(
<PreparePullRequestForm<{ main: string }>
defaultValues={{ main: 'default' }}
render={({ register }) => (
@@ -67,9 +67,9 @@ describe('<PreparePullRequestForm />', () => {
);
await act(async () => {
await userEvent.clear(getByLabelText('Main Field'));
await userEvent.type(getByLabelText('Main Field'), 'My Text');
await userEvent.click(getByRole('button', { name: /submit/i }));
await userEvent.clear(screen.getByLabelText('Main Field'));
await userEvent.type(screen.getByLabelText('Main Field'), 'My Text');
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
});
expect(onSubmitFn).toHaveBeenCalledTimes(1);
@@ -79,7 +79,7 @@ describe('<PreparePullRequestForm />', () => {
it('registers required attribute', async () => {
const onSubmitFn = jest.fn();
const { queryByText, getByRole } = render(
render(
<PreparePullRequestForm<{ main: string }>
defaultValues={{}}
render={({ formState, register }) => (
@@ -100,13 +100,17 @@ describe('<PreparePullRequestForm />', () => {
/>,
);
expect(queryByText('Error in required main field')).not.toBeInTheDocument();
expect(
screen.queryByText('Error in required main field'),
).not.toBeInTheDocument();
await act(async () => {
await userEvent.click(getByRole('button', { name: /submit/i }));
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
});
expect(onSubmitFn).not.toHaveBeenCalled();
expect(queryByText('Error in required main field')).toBeInTheDocument();
expect(
screen.queryByText('Error in required main field'),
).toBeInTheDocument();
});
});
@@ -15,7 +15,7 @@
*/
import { makeStyles } from '@material-ui/core';
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import React from 'react';
import { PreviewPullRequestComponent } from './PreviewPullRequestComponent';
@@ -28,15 +28,15 @@ const useStyles = makeStyles({
describe('<PreviewPullRequestComponent />', () => {
it('renders without exploding', async () => {
const { getByText } = render(
render(
<PreviewPullRequestComponent
title="My Title"
description="My **description**"
/>,
);
const title = getByText('My Title');
const description = getByText('description', { selector: 'strong' });
const title = screen.getByText('My Title');
const description = screen.getByText('description', { selector: 'strong' });
expect(title).toBeInTheDocument();
expect(title).toBeVisible();
expect(description).toBeInTheDocument();
@@ -46,7 +46,7 @@ describe('<PreviewPullRequestComponent />', () => {
it('renders card with custom styles', async () => {
const { result } = renderHook(() => useStyles());
const { getByText } = render(
render(
<PreviewPullRequestComponent
title="My Title"
description="My **description**"
@@ -54,8 +54,8 @@ describe('<PreviewPullRequestComponent />', () => {
/>,
);
const title = getByText('My Title');
const description = getByText('description', { selector: 'strong' });
const title = screen.getByText('My Title');
const description = screen.getByText('description', { selector: 'strong' });
expect(title).toBeInTheDocument();
expect(title).not.toBeVisible();
expect(description).toBeInTheDocument();
@@ -65,7 +65,7 @@ describe('<PreviewPullRequestComponent />', () => {
it('renders with custom styles', async () => {
const { result } = renderHook(() => useStyles());
const { getByText } = render(
render(
<PreviewPullRequestComponent
title="My Title"
description="My **description**"
@@ -73,8 +73,8 @@ describe('<PreviewPullRequestComponent />', () => {
/>,
);
const title = getByText('My Title');
const description = getByText('description', { selector: 'strong' });
const title = screen.getByText('My Title');
const description = screen.getByText('description', { selector: 'strong' });
expect(title).toBeInTheDocument();
expect(title).toBeVisible();
expect(description).toBeInTheDocument();
@@ -102,7 +102,7 @@ describe('<StepPrepareCreatePullRequest />', () => {
catalogApi.getEntities.mockReturnValue(Promise.resolve({ items: [] }));
await act(async () => {
const { findByText } = render(
render(
<StepPrepareCreatePullRequest
analyzeResult={analyzeResult}
onPrepare={onPrepareFn}
@@ -122,8 +122,10 @@ describe('<StepPrepareCreatePullRequest />', () => {
},
);
const title = await findByText('My title');
const description = await findByText('body', { selector: 'strong' });
const title = await screen.findByText('My title');
const description = await screen.findByText('body', {
selector: 'strong',
});
expect(title).toBeInTheDocument();
expect(title).toBeVisible();
expect(description).toBeInTheDocument();
@@ -15,7 +15,7 @@
*/
import { renderInTestApp } from '@backstage/test-utils';
import { act } from '@testing-library/react';
import { act, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { AnalyzeResult } from '../../api';
@@ -58,7 +58,7 @@ describe('<StepPrepareSelectLocations />', () => {
});
it('renders display locations to be added', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
onPrepare={() => undefined}
@@ -66,15 +66,15 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
expect(rendered.getByText('url-1')).toBeInTheDocument();
expect(rendered.getByText('url-2')).toBeInTheDocument();
expect(screen.getByText('url-1')).toBeInTheDocument();
expect(screen.getByText('url-2')).toBeInTheDocument();
expect(
rendered.queryByText(/Select one or more locations/),
screen.queryByText(/Select one or more locations/),
).toBeInTheDocument();
expect(
rendered.queryByText(/locations already exist/),
screen.queryByText(/locations already exist/),
).not.toBeInTheDocument();
expect(rendered.getByRole('button', { name: /Review/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /Review/i })).toBeDisabled();
});
it('should display existing locations only', async () => {
@@ -95,7 +95,7 @@ describe('<StepPrepareSelectLocations />', () => {
],
} as Extract<AnalyzeResult, { type: 'locations' }>;
const rendered = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResultWithExistingLocation}
onPrepare={() => undefined}
@@ -103,15 +103,15 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
expect(rendered.getByText(/my-target/)).toBeInTheDocument();
expect(rendered.queryByText(/locations already exist/)).toBeInTheDocument();
expect(screen.getByText(/my-target/)).toBeInTheDocument();
expect(screen.queryByText(/locations already exist/)).toBeInTheDocument();
expect(
rendered.queryByText(/Select one or more locations/),
screen.queryByText(/Select one or more locations/),
).not.toBeInTheDocument();
});
it('should select and deselect all', async () => {
const { getByRole, getAllByRole } = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
onPrepare={() => undefined}
@@ -119,27 +119,31 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
const checkboxes = getAllByRole('checkbox');
const checkboxes = screen.getAllByRole('checkbox');
checkboxes.forEach(c => expect(c).not.toBeChecked());
expect(getByRole('button', { name: /Review/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /Review/i })).toBeDisabled();
await act(async () => {
await userEvent.click(getByRole('button', { name: /Select All/i }));
await userEvent.click(
screen.getByRole('button', { name: /Select All/i }),
);
});
checkboxes.forEach(c => expect(c).toBeChecked());
expect(getByRole('button', { name: /Review/i })).not.toBeDisabled();
expect(screen.getByRole('button', { name: /Review/i })).not.toBeDisabled();
await act(async () => {
await userEvent.click(getByRole('button', { name: /Select All/i }));
await userEvent.click(
screen.getByRole('button', { name: /Select All/i }),
);
});
checkboxes.forEach(c => expect(c).not.toBeChecked());
expect(getByRole('button', { name: /Review/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /Review/i })).toBeDisabled();
});
it('should preselect prepared locations', async () => {
const { getAllByRole } = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
prepareResult={{
@@ -151,7 +155,7 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
const checkboxes = getAllByRole('checkbox');
const checkboxes = screen.getAllByRole('checkbox');
expect(checkboxes[0]).not.toBeChecked();
expect(checkboxes[1]).toBeChecked();
@@ -159,7 +163,7 @@ describe('<StepPrepareSelectLocations />', () => {
});
it('should select items', async () => {
const { getAllByRole } = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
onPrepare={() => undefined}
@@ -167,7 +171,7 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
const checkboxes = getAllByRole('checkbox');
const checkboxes = screen.getAllByRole('checkbox');
checkboxes.forEach(c => expect(c).not.toBeChecked());
await act(async () => {
@@ -188,7 +192,7 @@ describe('<StepPrepareSelectLocations />', () => {
it('should go back', async () => {
const onGoBack = jest.fn();
const { getByRole } = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
onPrepare={() => undefined}
@@ -197,7 +201,7 @@ describe('<StepPrepareSelectLocations />', () => {
);
await act(async () => {
await userEvent.click(getByRole('button', { name: /Back/i }));
await userEvent.click(screen.getByRole('button', { name: /Back/i }));
});
expect(onGoBack).toHaveBeenCalledTimes(1);
@@ -206,7 +210,7 @@ describe('<StepPrepareSelectLocations />', () => {
it('should submit', async () => {
const onPrepare = jest.fn();
const { getAllByRole, getByRole } = await renderInTestApp(
await renderInTestApp(
<StepPrepareSelectLocations
analyzeResult={analyzeResult}
onPrepare={onPrepare}
@@ -214,14 +218,14 @@ describe('<StepPrepareSelectLocations />', () => {
/>,
);
const checkboxes = getAllByRole('checkbox');
const checkboxes = screen.getAllByRole('checkbox');
await act(async () => {
await userEvent.click(checkboxes[1]);
});
await act(async () => {
await userEvent.click(getByRole('button', { name: /Review/i }));
await userEvent.click(screen.getByRole('button', { name: /Review/i }));
});
expect(onPrepare).toHaveBeenCalledTimes(1);
+5 -1
View File
@@ -1 +1,5 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname);
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname, {
rules: {
'testing-library/prefer-screen-queries': 'error',
},
});
@@ -19,7 +19,7 @@ import { Entity } from '@backstage/catalog-model';
import { ApiProvider } from '@backstage/core-app-api';
import { alertApiRef } from '@backstage/core-plugin-api';
import { renderWithEffects, TestApiRegistry } from '@backstage/test-utils';
import { fireEvent, waitFor } from '@testing-library/react';
import { fireEvent, waitFor, screen } from '@testing-library/react';
import { capitalize } from 'lodash';
import { default as React } from 'react';
import { catalogApiRef } from '../../api';
@@ -75,7 +75,7 @@ describe('<EntityKindPicker/>', () => {
);
it('renders available entity kinds', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{ filters: { kind: new EntityKindFilter('component') } }}
@@ -84,16 +84,16 @@ describe('<EntityKindPicker/>', () => {
</MockEntityListContextProvider>
</ApiProvider>,
);
expect(rendered.getByText('Kind')).toBeInTheDocument();
expect(screen.getByText('Kind')).toBeInTheDocument();
const input = rendered.getByTestId('select');
const input = screen.getByTestId('select');
fireEvent.click(input);
await waitFor(() => rendered.getByText('Domain'));
await waitFor(() => screen.getByText('Domain'));
entities.forEach(entity => {
expect(
rendered.getByRole('option', {
screen.getByRole('option', {
name: capitalize(entity.kind as string),
}),
).toBeInTheDocument();
@@ -102,7 +102,7 @@ describe('<EntityKindPicker/>', () => {
it('sets the selected kind filter', async () => {
const updateFilters = jest.fn();
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{
@@ -114,11 +114,11 @@ describe('<EntityKindPicker/>', () => {
</MockEntityListContextProvider>
</ApiProvider>,
);
const input = rendered.getByTestId('select');
const input = screen.getByTestId('select');
fireEvent.click(input);
await waitFor(() => rendered.getByText('Domain'));
fireEvent.click(rendered.getByText('Domain'));
await waitFor(() => screen.getByText('Domain'));
fireEvent.click(screen.getByText('Domain'));
expect(updateFilters).toHaveBeenLastCalledWith({
kind: new EntityKindFilter('domain'),
@@ -15,7 +15,7 @@
*/
import { Entity } from '@backstage/catalog-model';
import { fireEvent, render } from '@testing-library/react';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { MockEntityListContextProvider } from '../../testUtils/providers';
import { EntityLifecycleFilter } from '../../filters';
@@ -56,36 +56,36 @@ const sampleEntities: Entity[] = [
describe('<EntityLifecyclePicker/>', () => {
it('renders all lifecycles', () => {
const rendered = render(
render(
<MockEntityListContextProvider
value={{ entities: sampleEntities, backendEntities: sampleEntities }}
>
<EntityLifecyclePicker />
</MockEntityListContextProvider>,
);
expect(rendered.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
fireEvent.click(rendered.getByTestId('lifecycle-picker-expand'));
fireEvent.click(screen.getByTestId('lifecycle-picker-expand'));
sampleEntities
.map(e => e.spec?.lifecycle!)
.forEach(lifecycle => {
expect(rendered.getByText(lifecycle as string)).toBeInTheDocument();
expect(screen.getByText(lifecycle as string)).toBeInTheDocument();
});
});
it('renders unique lifecycles in alphabetical order', () => {
const rendered = render(
render(
<MockEntityListContextProvider
value={{ entities: sampleEntities, backendEntities: sampleEntities }}
>
<EntityLifecyclePicker />
</MockEntityListContextProvider>,
);
expect(rendered.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
fireEvent.click(rendered.getByTestId('lifecycle-picker-expand'));
fireEvent.click(screen.getByTestId('lifecycle-picker-expand'));
expect(rendered.getAllByRole('option').map(o => o.textContent)).toEqual([
expect(screen.getAllByRole('option').map(o => o.textContent)).toEqual([
'experimental',
'production',
]);
@@ -114,7 +114,7 @@ describe('<EntityLifecyclePicker/>', () => {
it('adds lifecycles to filters', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -129,8 +129,8 @@ describe('<EntityLifecyclePicker/>', () => {
lifecycles: undefined,
});
fireEvent.click(rendered.getByTestId('lifecycle-picker-expand'));
fireEvent.click(rendered.getByText('production'));
fireEvent.click(screen.getByTestId('lifecycle-picker-expand'));
fireEvent.click(screen.getByText('production'));
expect(updateFilters).toHaveBeenLastCalledWith({
lifecycles: new EntityLifecycleFilter(['production']),
});
@@ -138,7 +138,7 @@ describe('<EntityLifecyclePicker/>', () => {
it('removes lifecycles from filters', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -153,10 +153,10 @@ describe('<EntityLifecyclePicker/>', () => {
expect(updateFilters).toHaveBeenLastCalledWith({
lifecycles: new EntityLifecycleFilter(['production']),
});
fireEvent.click(rendered.getByTestId('lifecycle-picker-expand'));
expect(rendered.getByLabelText('production')).toBeChecked();
fireEvent.click(screen.getByTestId('lifecycle-picker-expand'));
expect(screen.getByLabelText('production')).toBeChecked();
fireEvent.click(rendered.getByLabelText('production'));
fireEvent.click(screen.getByLabelText('production'));
expect(updateFilters).toHaveBeenLastCalledWith({
lifecycles: undefined,
});
@@ -15,7 +15,7 @@
*/
import { Entity, parseEntityRef } from '@backstage/catalog-model';
import { fireEvent, render } from '@testing-library/react';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { MockEntityListContextProvider } from '../../testUtils/providers';
import { EntityOwnerFilter } from '../../filters';
@@ -69,36 +69,36 @@ const sampleEntities: Entity[] = [
describe('<EntityOwnerPicker/>', () => {
it('renders all owners', () => {
const rendered = render(
render(
<MockEntityListContextProvider
value={{ entities: sampleEntities, backendEntities: sampleEntities }}
>
<EntityOwnerPicker />
</MockEntityListContextProvider>,
);
expect(rendered.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner')).toBeInTheDocument();
fireEvent.click(rendered.getByTestId('owner-picker-expand'));
fireEvent.click(screen.getByTestId('owner-picker-expand'));
sampleEntities
.flatMap(e => e.relations?.map(r => parseEntityRef(r.targetRef).name))
.forEach(owner => {
expect(rendered.getByText(owner as string)).toBeInTheDocument();
expect(screen.getByText(owner as string)).toBeInTheDocument();
});
});
it('renders unique owners in alphabetical order', () => {
const rendered = render(
render(
<MockEntityListContextProvider
value={{ entities: sampleEntities, backendEntities: sampleEntities }}
>
<EntityOwnerPicker />
</MockEntityListContextProvider>,
);
expect(rendered.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner')).toBeInTheDocument();
fireEvent.click(rendered.getByTestId('owner-picker-expand'));
fireEvent.click(screen.getByTestId('owner-picker-expand'));
expect(rendered.getAllByRole('option').map(o => o.textContent)).toEqual([
expect(screen.getAllByRole('option').map(o => o.textContent)).toEqual([
'another-owner',
'some-owner',
'some-owner-2',
@@ -128,7 +128,7 @@ describe('<EntityOwnerPicker/>', () => {
it('adds owners to filters', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -143,8 +143,8 @@ describe('<EntityOwnerPicker/>', () => {
owners: undefined,
});
fireEvent.click(rendered.getByTestId('owner-picker-expand'));
fireEvent.click(rendered.getByText('some-owner'));
fireEvent.click(screen.getByTestId('owner-picker-expand'));
fireEvent.click(screen.getByText('some-owner'));
expect(updateFilters).toHaveBeenLastCalledWith({
owners: new EntityOwnerFilter(['some-owner']),
});
@@ -152,7 +152,7 @@ describe('<EntityOwnerPicker/>', () => {
it('removes owners from filters', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -167,10 +167,10 @@ describe('<EntityOwnerPicker/>', () => {
expect(updateFilters).toHaveBeenLastCalledWith({
owners: new EntityOwnerFilter(['some-owner']),
});
fireEvent.click(rendered.getByTestId('owner-picker-expand'));
expect(rendered.getByLabelText('some-owner')).toBeChecked();
fireEvent.click(screen.getByTestId('owner-picker-expand'));
expect(screen.getByLabelText('some-owner')).toBeChecked();
fireEvent.click(rendered.getByLabelText('some-owner'));
fireEvent.click(screen.getByLabelText('some-owner'));
expect(updateFilters).toHaveBeenLastCalledWith({
owner: undefined,
});
@@ -15,7 +15,7 @@
*/
import { Entity } from '@backstage/catalog-model';
import { fireEvent, render } from '@testing-library/react';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { EntityErrorFilter, EntityOrphanFilter } from '../../filters';
import { MockEntityListContextProvider } from '../../testUtils/providers';
@@ -52,23 +52,23 @@ const sampleEntities: Entity[] = [
describe('<EntityProcessingStatusPicker/>', () => {
it('renders all processing status options', () => {
const rendered = render(
render(
<MockEntityListContextProvider
value={{ entities: sampleEntities, backendEntities: sampleEntities }}
>
<EntityProcessingStatusPicker />
</MockEntityListContextProvider>,
);
expect(rendered.getByText('Processing Status')).toBeInTheDocument();
expect(screen.getByText('Processing Status')).toBeInTheDocument();
fireEvent.click(rendered.getByTestId('processing-status-picker-expand'));
expect(rendered.getByText('Is Orphan')).toBeInTheDocument();
expect(rendered.getByText('Has Error')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('processing-status-picker-expand'));
expect(screen.getByText('Is Orphan')).toBeInTheDocument();
expect(screen.getByText('Has Error')).toBeInTheDocument();
});
it('adds orphan to orphan filter', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -80,8 +80,8 @@ describe('<EntityProcessingStatusPicker/>', () => {
</MockEntityListContextProvider>,
);
fireEvent.click(rendered.getByTestId('processing-status-picker-expand'));
fireEvent.click(rendered.getByText('Is Orphan'));
fireEvent.click(screen.getByTestId('processing-status-picker-expand'));
fireEvent.click(screen.getByText('Is Orphan'));
expect(updateFilters).toHaveBeenCalledWith({
orphan: new EntityOrphanFilter(true),
});
@@ -89,7 +89,7 @@ describe('<EntityProcessingStatusPicker/>', () => {
it('adds error to error filter', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -101,8 +101,8 @@ describe('<EntityProcessingStatusPicker/>', () => {
</MockEntityListContextProvider>,
);
fireEvent.click(rendered.getByTestId('processing-status-picker-expand'));
fireEvent.click(rendered.getByText('Has Error'));
fireEvent.click(screen.getByTestId('processing-status-picker-expand'));
fireEvent.click(screen.getByText('Has Error'));
expect(updateFilters).toHaveBeenCalledWith({
error: new EntityErrorFilter(true),
});
@@ -110,7 +110,7 @@ describe('<EntityProcessingStatusPicker/>', () => {
it('remove orphan from orphan filter', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -122,8 +122,8 @@ describe('<EntityProcessingStatusPicker/>', () => {
</MockEntityListContextProvider>,
);
fireEvent.click(rendered.getByTestId('processing-status-picker-expand'));
fireEvent.click(rendered.getByText('Is Orphan'));
fireEvent.click(screen.getByTestId('processing-status-picker-expand'));
fireEvent.click(screen.getByText('Is Orphan'));
expect(updateFilters).toHaveBeenCalledWith({
orphan: undefined,
});
@@ -131,7 +131,7 @@ describe('<EntityProcessingStatusPicker/>', () => {
it('remove error from error filter', () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<MockEntityListContextProvider
value={{
entities: sampleEntities,
@@ -143,8 +143,8 @@ describe('<EntityProcessingStatusPicker/>', () => {
</MockEntityListContextProvider>,
);
fireEvent.click(rendered.getByTestId('processing-status-picker-expand'));
fireEvent.click(rendered.getByText('Has Error'));
fireEvent.click(screen.getByTestId('processing-status-picker-expand'));
fireEvent.click(screen.getByText('Has Error'));
expect(updateFilters).toHaveBeenCalledWith({
error: undefined,
});
@@ -15,6 +15,7 @@
*/
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { entityRouteRef } from '../../routes';
import { EntityRefLink } from './EntityRefLink';
@@ -33,16 +34,13 @@ describe('<EntityRefLink />', () => {
lifecycle: 'production',
},
};
const { getByText } = await renderInTestApp(
<EntityRefLink entityRef={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLink entityRef={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
});
expect(getByText('component:software')).toHaveAttribute(
expect(screen.getByText('component:software')).toHaveAttribute(
'href',
'/catalog/default/component/software',
);
@@ -62,15 +60,12 @@ describe('<EntityRefLink />', () => {
lifecycle: 'production',
},
};
const { getByText } = await renderInTestApp(
<EntityRefLink entityRef={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLink entityRef={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
expect(getByText('component:test/software')).toHaveAttribute(
});
expect(screen.getByText('component:test/software')).toHaveAttribute(
'href',
'/catalog/test/component/software',
);
@@ -90,7 +85,7 @@ describe('<EntityRefLink />', () => {
lifecycle: 'production',
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityRefLink entityRef={entity} defaultKind="Component" />,
{
mountedRoutes: {
@@ -98,7 +93,7 @@ describe('<EntityRefLink />', () => {
},
},
);
expect(getByText('test/software')).toHaveAttribute(
expect(screen.getByText('test/software')).toHaveAttribute(
'href',
'/catalog/test/component/software',
);
@@ -110,15 +105,12 @@ describe('<EntityRefLink />', () => {
namespace: 'default',
name: 'software',
};
const { getByText } = await renderInTestApp(
<EntityRefLink entityRef={entityName} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLink entityRef={entityName} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
expect(getByText('component:software')).toHaveAttribute(
});
expect(screen.getByText('component:software')).toHaveAttribute(
'href',
'/catalog/default/component/software',
);
@@ -130,15 +122,12 @@ describe('<EntityRefLink />', () => {
namespace: 'test',
name: 'software',
};
const { getByText } = await renderInTestApp(
<EntityRefLink entityRef={entityName} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLink entityRef={entityName} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
expect(getByText('component:test/software')).toHaveAttribute(
});
expect(screen.getByText('component:test/software')).toHaveAttribute(
'href',
'/catalog/test/component/software',
);
@@ -150,7 +139,7 @@ describe('<EntityRefLink />', () => {
namespace: 'test',
name: 'software',
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityRefLink entityRef={entityName} defaultKind="component" />,
{
mountedRoutes: {
@@ -158,7 +147,7 @@ describe('<EntityRefLink />', () => {
},
},
);
expect(getByText('test/software')).toHaveAttribute(
expect(screen.getByText('test/software')).toHaveAttribute(
'href',
'/catalog/test/component/software',
);
@@ -170,7 +159,7 @@ describe('<EntityRefLink />', () => {
namespace: 'test',
name: 'software',
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityRefLink entityRef={entityName} defaultKind="component">
Custom Children
</EntityRefLink>,
@@ -180,7 +169,7 @@ describe('<EntityRefLink />', () => {
},
},
);
expect(getByText('Custom Children')).toHaveAttribute(
expect(screen.getByText('Custom Children')).toHaveAttribute(
'href',
'/catalog/test/component/software',
);
@@ -15,6 +15,7 @@
*/
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { entityRouteRef } from '../../routes';
import { EntityRefLinks } from './EntityRefLinks';
@@ -28,15 +29,12 @@ describe('<EntityRefLinks />', () => {
name: 'software',
},
];
const { getByText } = await renderInTestApp(
<EntityRefLinks entityRefs={entityNames} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLinks entityRefs={entityNames} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
expect(getByText('component:software')).toHaveAttribute(
});
expect(screen.getByText('component:software')).toHaveAttribute(
'href',
'/catalog/default/component/software',
);
@@ -55,20 +53,17 @@ describe('<EntityRefLinks />', () => {
name: 'interface',
},
];
const { getByText } = await renderInTestApp(
<EntityRefLinks entityRefs={entityNames} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
await renderInTestApp(<EntityRefLinks entityRefs={entityNames} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name/*': entityRouteRef,
},
);
expect(getByText(',')).toBeInTheDocument();
expect(getByText('component:software')).toHaveAttribute(
});
expect(screen.getByText(',')).toBeInTheDocument();
expect(screen.getByText('component:software')).toHaveAttribute(
'href',
'/catalog/default/component/software',
);
expect(getByText('api:interface')).toHaveAttribute(
expect(screen.getByText('api:interface')).toHaveAttribute(
'href',
'/catalog/default/api/interface',
);
@@ -16,6 +16,7 @@
import { FetchedEntityRefLinks } from './FetchedEntityRefLinks';
import { entityRouteRef } from '../../routes';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import { Entity } from '@backstage/catalog-model';
import React from 'react';
import { JsonObject } from '@backstage/types';
@@ -60,7 +61,7 @@ describe('<FetchedEntityRefLinks />', () => {
}),
};
const rendered = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<FetchedEntityRefLinks entityRefs={entityRefs} getTitle={getTitle} />
</TestApiProvider>,
@@ -71,12 +72,12 @@ describe('<FetchedEntityRefLinks />', () => {
},
);
expect(rendered.getByText('SOFTWARE')).toHaveAttribute(
expect(screen.getByText('SOFTWARE')).toHaveAttribute(
'href',
'/catalog/default/component/software',
);
expect(rendered.getByText('INTERFACE')).toHaveAttribute(
expect(screen.getByText('INTERFACE')).toHaveAttribute(
'href',
'/catalog/default/api/interface',
);
@@ -111,7 +112,7 @@ describe('<FetchedEntityRefLinks />', () => {
const catalogApi: Partial<CatalogApi> = {};
const rendered = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<FetchedEntityRefLinks entityRefs={entityRefs} getTitle={getTitle} />
</TestApiProvider>,
@@ -122,12 +123,12 @@ describe('<FetchedEntityRefLinks />', () => {
},
);
expect(rendered.getByText('TOOL')).toHaveAttribute(
expect(screen.getByText('TOOL')).toHaveAttribute(
'href',
'/catalog/default/component/tool',
);
expect(rendered.getByText('IMPLEMENTATION')).toHaveAttribute(
expect(screen.getByText('IMPLEMENTATION')).toHaveAttribute(
'href',
'/catalog/default/api/implementation',
);
@@ -189,7 +190,7 @@ describe('<FetchedEntityRefLinks />', () => {
}),
};
const rendered = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<FetchedEntityRefLinks entityRefs={entityRefs} getTitle={getTitle} />
</TestApiProvider>,
@@ -200,17 +201,17 @@ describe('<FetchedEntityRefLinks />', () => {
},
);
expect(rendered.getByText('TOOL')).toHaveAttribute(
expect(screen.getByText('TOOL')).toHaveAttribute(
'href',
'/catalog/default/component/tool',
);
expect(rendered.getByText('IMPLEMENTATION')).toHaveAttribute(
expect(screen.getByText('IMPLEMENTATION')).toHaveAttribute(
'href',
'/catalog/default/api/implementation',
);
expect(rendered.getByText('INTERFACE')).toHaveAttribute(
expect(screen.getByText('INTERFACE')).toHaveAttribute(
'href',
'/catalog/default/component/interface',
);
@@ -15,7 +15,7 @@
*/
import React from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { fireEvent, render, waitFor, screen } from '@testing-library/react';
import { EntitySearchBar } from './EntitySearchBar';
import { DefaultEntityFilters } from '../../hooks/useEntityListProvider';
import { EntityTextFilter } from '../../filters';
@@ -29,13 +29,13 @@ describe('EntitySearchBar', () => {
text: new EntityTextFilter('hello'),
};
const { getByDisplayValue } = render(
render(
<MockEntityListContextProvider value={{ updateFilters, filters }}>
<EntitySearchBar />
</MockEntityListContextProvider>,
);
const searchInput = getByDisplayValue('hello');
const searchInput = screen.getByDisplayValue('hello');
expect(searchInput).toBeInTheDocument();
fireEvent.change(searchInput, { target: { value: 'world' } });
@@ -16,13 +16,13 @@
import { Entity } from '@backstage/catalog-model';
import { renderInTestApp } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { EntityTable } from './EntityTable';
describe('<EntityTable />', () => {
it('shows empty table', async () => {
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityTable
title="Entities"
entities={[]}
@@ -31,8 +31,8 @@ describe('<EntityTable />', () => {
/>,
);
expect(getByText('Entities')).toBeInTheDocument();
expect(getByText('EMPTY')).toBeInTheDocument();
expect(screen.getByText('Entities')).toBeInTheDocument();
expect(screen.getByText('EMPTY')).toBeInTheDocument();
});
it('shows entities', async () => {
@@ -47,7 +47,7 @@ describe('<EntityTable />', () => {
},
];
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityTable
title="Entities"
entities={entities}
@@ -62,7 +62,7 @@ describe('<EntityTable />', () => {
);
await waitFor(() => {
expect(getByText('my-entity')).toBeInTheDocument();
expect(screen.getByText('my-entity')).toBeInTheDocument();
});
});
});
@@ -21,7 +21,7 @@ import {
SystemEntity,
} from '@backstage/catalog-model';
import { renderInTestApp } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { entityRouteRef } from '../../routes';
import { EntityTable } from './EntityTable';
@@ -54,7 +54,7 @@ describe('systemEntityColumns', () => {
},
];
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityTable
title="My Systems"
entities={entities}
@@ -69,10 +69,10 @@ describe('systemEntityColumns', () => {
);
await waitFor(() => {
expect(getByText('my-namespace/my-system')).toBeInTheDocument();
expect(getByText('my-namespace/my-domain')).toBeInTheDocument();
expect(getByText('test')).toBeInTheDocument();
expect(getByText(/Some/)).toBeInTheDocument();
expect(screen.getByText('my-namespace/my-system')).toBeInTheDocument();
expect(screen.getByText('my-namespace/my-domain')).toBeInTheDocument();
expect(screen.getByText('test')).toBeInTheDocument();
expect(screen.getByText(/Some/)).toBeInTheDocument();
});
});
});
@@ -106,7 +106,7 @@ describe('componentEntityColumns', () => {
},
];
const { getByText } = await renderInTestApp(
await renderInTestApp(
<EntityTable
title="My Components"
entities={entities}
@@ -121,12 +121,12 @@ describe('componentEntityColumns', () => {
);
await waitFor(() => {
expect(getByText('my-namespace/my-component')).toBeInTheDocument();
expect(getByText('my-namespace/my-system')).toBeInTheDocument();
expect(getByText('test')).toBeInTheDocument();
expect(getByText('production')).toBeInTheDocument();
expect(getByText('service')).toBeInTheDocument();
expect(getByText(/Some/)).toBeInTheDocument();
expect(screen.getByText('my-namespace/my-component')).toBeInTheDocument();
expect(screen.getByText('my-namespace/my-system')).toBeInTheDocument();
expect(screen.getByText('test')).toBeInTheDocument();
expect(screen.getByText('production')).toBeInTheDocument();
expect(screen.getByText('service')).toBeInTheDocument();
expect(screen.getByText(/Some/)).toBeInTheDocument();
});
});
});
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { fireEvent, render, waitFor } from '@testing-library/react';
import { fireEvent, render, waitFor, screen } from '@testing-library/react';
import React from 'react';
import { MockEntityListContextProvider } from '../../testUtils/providers';
import { EntityTagFilter } from '../../filters';
@@ -35,34 +35,34 @@ describe('<EntityTagPicker/>', () => {
} as unknown as CatalogApi;
it('renders all tags', async () => {
const rendered = render(
render(
<TestApiProvider apis={[[catalogApiRef, mockCatalogApiRef]]}>
<MockEntityListContextProvider value={{}}>
<EntityTagPicker />
</MockEntityListContextProvider>
</TestApiProvider>,
);
await waitFor(() => expect(rendered.getByText('Tags')).toBeInTheDocument());
await waitFor(() => expect(screen.getByText('Tags')).toBeInTheDocument());
fireEvent.click(rendered.getByTestId('tag-picker-expand'));
fireEvent.click(screen.getByTestId('tag-picker-expand'));
tags.forEach(tag => {
expect(rendered.getByText(tag)).toBeInTheDocument();
expect(screen.getByText(tag)).toBeInTheDocument();
});
});
it('renders unique tags in alphabetical order', async () => {
const rendered = render(
render(
<TestApiProvider apis={[[catalogApiRef, mockCatalogApiRef]]}>
<MockEntityListContextProvider value={{}}>
<EntityTagPicker />
</MockEntityListContextProvider>
</TestApiProvider>,
);
await waitFor(() => expect(rendered.getByText('Tags')).toBeInTheDocument());
await waitFor(() => expect(screen.getByText('Tags')).toBeInTheDocument());
fireEvent.click(rendered.getByTestId('tag-picker-expand'));
fireEvent.click(screen.getByTestId('tag-picker-expand'));
expect(rendered.getAllByRole('option').map(o => o.textContent)).toEqual([
expect(screen.getAllByRole('option').map(o => o.textContent)).toEqual([
'tag1',
'tag2',
'tag3',
@@ -71,18 +71,18 @@ describe('<EntityTagPicker/>', () => {
});
it('renders tags with counts', async () => {
const rendered = render(
render(
<TestApiProvider apis={[[catalogApiRef, mockCatalogApiRef]]}>
<MockEntityListContextProvider value={{}}>
<EntityTagPicker showCounts />
</MockEntityListContextProvider>
</TestApiProvider>,
);
await waitFor(() => expect(rendered.getByText('Tags')).toBeInTheDocument());
await waitFor(() => expect(screen.getByText('Tags')).toBeInTheDocument());
fireEvent.click(rendered.getByTestId('tag-picker-expand'));
fireEvent.click(screen.getByTestId('tag-picker-expand'));
expect(rendered.getAllByRole('option').map(o => o.textContent)).toEqual([
expect(screen.getAllByRole('option').map(o => o.textContent)).toEqual([
'tag1 (0)',
'tag2 (1)',
'tag3 (2)',
@@ -115,7 +115,7 @@ describe('<EntityTagPicker/>', () => {
it('adds tags to filters', async () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<TestApiProvider apis={[[catalogApiRef, mockCatalogApiRef]]}>
<MockEntityListContextProvider
value={{
@@ -132,8 +132,8 @@ describe('<EntityTagPicker/>', () => {
}),
);
fireEvent.click(rendered.getByTestId('tag-picker-expand'));
fireEvent.click(rendered.getByText('tag1'));
fireEvent.click(screen.getByTestId('tag-picker-expand'));
fireEvent.click(screen.getByText('tag1'));
expect(updateFilters).toHaveBeenLastCalledWith({
tags: new EntityTagFilter(['tag1']),
});
@@ -141,7 +141,7 @@ describe('<EntityTagPicker/>', () => {
it('removes tags from filters', async () => {
const updateFilters = jest.fn();
const rendered = render(
render(
<TestApiProvider apis={[[catalogApiRef, mockCatalogApiRef]]}>
<MockEntityListContextProvider
value={{
@@ -158,10 +158,10 @@ describe('<EntityTagPicker/>', () => {
tags: new EntityTagFilter(['tag1']),
}),
);
fireEvent.click(rendered.getByTestId('tag-picker-expand'));
expect(rendered.getByLabelText('tag1')).toBeChecked();
fireEvent.click(screen.getByTestId('tag-picker-expand'));
expect(screen.getByLabelText('tag1')).toBeChecked();
fireEvent.click(rendered.getByLabelText('tag1'));
fireEvent.click(screen.getByLabelText('tag1'));
expect(updateFilters).toHaveBeenLastCalledWith({
tags: undefined,
});
@@ -15,13 +15,12 @@
*/
import React from 'react';
import { fireEvent, waitFor } from '@testing-library/react';
import { fireEvent, waitFor, screen } from '@testing-library/react';
import { Entity } from '@backstage/catalog-model';
import { EntityTypePicker } from './EntityTypePicker';
import { MockEntityListContextProvider } from '../../testUtils/providers';
import { catalogApiRef } from '../../api';
import { EntityKindFilter, EntityTypeFilter } from '../../filters';
import { alertApiRef } from '@backstage/core-plugin-api';
import { ApiProvider } from '@backstage/core-app-api';
import { renderWithEffects, TestApiRegistry } from '@backstage/test-utils';
@@ -84,7 +83,7 @@ const apis = TestApiRegistry.from(
describe('<EntityTypePicker/>', () => {
it('renders available entity types', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{ filters: { kind: new EntityKindFilter('component') } }}
@@ -93,23 +92,21 @@ describe('<EntityTypePicker/>', () => {
</MockEntityListContextProvider>
</ApiProvider>,
);
expect(rendered.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
const input = rendered.getByTestId('select');
const input = screen.getByTestId('select');
fireEvent.click(input);
await waitFor(() => rendered.getByText('service'));
await waitFor(() => screen.getByText('service'));
entities.forEach(entity => {
expect(
rendered.getByText(entity.spec!.type as string),
).toBeInTheDocument();
expect(screen.getByText(entity.spec!.type as string)).toBeInTheDocument();
});
});
it('sets the selected type filter', async () => {
const updateFilters = jest.fn();
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{
@@ -121,18 +118,18 @@ describe('<EntityTypePicker/>', () => {
</MockEntityListContextProvider>
</ApiProvider>,
);
const input = rendered.getByTestId('select');
const input = screen.getByTestId('select');
fireEvent.click(input);
await waitFor(() => rendered.getByText('service'));
fireEvent.click(rendered.getByText('service'));
await waitFor(() => screen.getByText('service'));
fireEvent.click(screen.getByText('service'));
expect(updateFilters).toHaveBeenLastCalledWith({
type: new EntityTypeFilter(['service']),
});
fireEvent.click(input);
fireEvent.click(rendered.getByText('all'));
fireEvent.click(screen.getByText('all'));
expect(updateFilters).toHaveBeenLastCalledWith({ type: undefined });
});
@@ -15,7 +15,7 @@
*/
import React from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { fireEvent, render, waitFor, screen } from '@testing-library/react';
import {
Entity,
RELATION_OWNED_BY,
@@ -27,7 +27,6 @@ import { EntityTagFilter, UserListFilter } from '../../filters';
import { CatalogApi } from '@backstage/catalog-client';
import { catalogApiRef } from '../../api';
import { MockStorageApi, TestApiRegistry } from '@backstage/test-utils';
import { ApiProvider } from '@backstage/core-app-api';
import {
ConfigApi,
@@ -144,7 +143,7 @@ const backendEntities: Entity[] = [
describe('<UserListPicker />', () => {
it('renders filter groups', () => {
const { queryByText } = render(
render(
<ApiProvider apis={apis}>
<MockEntityListContextProvider value={{ backendEntities }}>
<UserListPicker />
@@ -152,12 +151,12 @@ describe('<UserListPicker />', () => {
</ApiProvider>,
);
expect(queryByText('Personal')).toBeInTheDocument();
expect(queryByText('Test Company')).toBeInTheDocument();
expect(screen.queryByText('Personal')).toBeInTheDocument();
expect(screen.queryByText('Test Company')).toBeInTheDocument();
});
it('renders filters', () => {
const { getAllByRole } = render(
render(
<ApiProvider apis={apis}>
<MockEntityListContextProvider value={{ backendEntities }}>
<UserListPicker />
@@ -166,12 +165,12 @@ describe('<UserListPicker />', () => {
);
expect(
getAllByRole('menuitem').map(({ textContent }) => textContent),
screen.getAllByRole('menuitem').map(({ textContent }) => textContent),
).toEqual(['Owned 1', 'Starred 1', 'All 4']);
});
it('includes counts alongside each filter', async () => {
const { getAllByRole } = render(
render(
<ApiProvider apis={apis}>
<MockEntityListContextProvider value={{ backendEntities }}>
<UserListPicker />
@@ -183,13 +182,13 @@ describe('<UserListPicker />', () => {
// menuitem itself, so we pick off the next sibling.
await waitFor(() => {
expect(
getAllByRole('menuitem').map(({ textContent }) => textContent),
screen.getAllByRole('menuitem').map(({ textContent }) => textContent),
).toEqual(['Owned 1', 'Starred 1', 'All 4']);
});
});
it('respects other frontend filters in counts', async () => {
const { getAllByRole } = render(
render(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{
@@ -204,7 +203,7 @@ describe('<UserListPicker />', () => {
await waitFor(() => {
expect(
getAllByRole('menuitem').map(({ textContent }) => textContent),
screen.getAllByRole('menuitem').map(({ textContent }) => textContent),
).toEqual(['Owned 1', 'Starred 0', 'All 2']);
});
});
@@ -229,7 +228,7 @@ describe('<UserListPicker />', () => {
it('updates user filter when a menuitem is selected', () => {
const updateFilters = jest.fn();
const { getByText } = render(
render(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{ backendEntities, updateFilters }}
@@ -239,7 +238,7 @@ describe('<UserListPicker />', () => {
</ApiProvider>,
);
fireEvent.click(getByText('Starred'));
fireEvent.click(screen.getByText('Starred'));
expect(updateFilters).toHaveBeenLastCalledWith({
user: new UserListFilter(
+5 -1
View File
@@ -1 +1,5 @@
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname);
module.exports = require('@backstage/cli/config/eslint-factory')(__dirname, {
rules: {
'testing-library/prefer-screen-queries': 'error',
},
});
+1
View File
@@ -49,6 +49,7 @@
"@material-ui/lab": "4.0.0-alpha.57",
"history": "^5.0.0",
"lodash": "^4.17.21",
"pluralize": "^8.0.0",
"react-helmet": "6.1.0",
"react-use": "^17.2.4",
"zen-observable": "^0.9.0"
@@ -28,6 +28,7 @@ import {
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import userEvent from '@testing-library/user-event';
import { screen } from '@testing-library/react';
import React from 'react';
import { viewTechDocRouteRef } from '../../routes';
import { AboutCard } from './AboutCard';
@@ -73,7 +74,7 @@ describe('<AboutCard />', () => {
],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -98,10 +99,10 @@ describe('<AboutCard />', () => {
},
);
expect(getByText('service')).toBeInTheDocument();
expect(getByText('user:guest')).toBeInTheDocument();
expect(getByText('production')).toBeInTheDocument();
expect(getByText('This is the description')).toBeInTheDocument();
expect(screen.getByText('service')).toBeInTheDocument();
expect(screen.getByText('user:guest')).toBeInTheDocument();
expect(screen.getByText('production')).toBeInTheDocument();
expect(screen.getByText('This is the description')).toBeInTheDocument();
});
it('renders "view source" link', async () => {
@@ -122,7 +123,7 @@ describe('<AboutCard />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -153,7 +154,7 @@ describe('<AboutCard />', () => {
},
},
);
expect(getByText('View Source').closest('a')).toHaveAttribute(
expect(screen.getByText('View Source').closest('a')).toHaveAttribute(
'href',
'https://github.com/backstage/backstage/blob/master/software.yaml',
);
@@ -177,7 +178,7 @@ describe('<AboutCard />', () => {
},
};
const { getByTitle } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -209,7 +210,7 @@ describe('<AboutCard />', () => {
},
);
const editLink = getByTitle('Edit Metadata').closest('a');
const editLink = screen.getByTitle('Edit Metadata').closest('a');
expect(editLink).toHaveAttribute(
'href',
'https://github.com/backstage/backstage/edit/master/software.yaml',
@@ -230,7 +231,7 @@ describe('<AboutCard />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -250,8 +251,8 @@ describe('<AboutCard />', () => {
},
},
);
expect(getByText('View Source')).toBeVisible();
expect(getByText('View Source').closest('a')).toBeNull();
expect(screen.getByText('View Source')).toBeVisible();
expect(screen.getByText('View Source').closest('a')).toBeNull();
});
it.each([
@@ -274,7 +275,7 @@ describe('<AboutCard />', () => {
},
};
const { getByTitle } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -299,7 +300,7 @@ describe('<AboutCard />', () => {
'component:default/software',
);
await userEvent.click(getByTitle('Schedule entity refresh'));
await userEvent.click(screen.getByTitle('Schedule entity refresh'));
expect(catalogApi.refreshEntity).toHaveBeenCalledWith(
'component:default/software',
@@ -320,7 +321,7 @@ describe('<AboutCard />', () => {
},
};
const { queryByTitle } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -341,7 +342,9 @@ describe('<AboutCard />', () => {
},
);
expect(queryByTitle('Schedule entity refresh')).not.toBeInTheDocument();
expect(
screen.queryByTitle('Schedule entity refresh'),
).not.toBeInTheDocument();
});
it('renders techdocs link', async () => {
@@ -361,7 +364,7 @@ describe('<AboutCard />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -394,7 +397,7 @@ describe('<AboutCard />', () => {
},
);
expect(getByText('View TechDocs').closest('a')).toHaveAttribute(
expect(screen.getByText('View TechDocs').closest('a')).toHaveAttribute(
'href',
'/docs/default/Component/software',
);
@@ -414,7 +417,7 @@ describe('<AboutCard />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -446,8 +449,8 @@ describe('<AboutCard />', () => {
},
);
expect(getByText('View TechDocs')).toBeVisible();
expect(getByText('View TechDocs').closest('a')).toBeNull();
expect(screen.getByText('View TechDocs')).toBeVisible();
expect(screen.getByText('View TechDocs').closest('a')).toBeNull();
});
it('renders disabled techdocs link when route is not bound', async () => {
@@ -467,7 +470,7 @@ describe('<AboutCard />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -499,7 +502,7 @@ describe('<AboutCard />', () => {
},
);
expect(getByText('View TechDocs')).toBeVisible();
expect(getByText('View TechDocs').closest('a')).toBeNull();
expect(screen.getByText('View TechDocs')).toBeVisible();
expect(screen.getByText('View TechDocs').closest('a')).toBeNull();
});
});
@@ -21,6 +21,7 @@ import {
} from '@backstage/catalog-model';
import { entityRouteRef } from '@backstage/plugin-catalog-react';
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { AboutContent } from './AboutContent';
@@ -62,32 +63,29 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:o');
expect(getByText('Domain')).toBeInTheDocument();
expect(getByText('Domain').nextSibling).toHaveTextContent('d');
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('s');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('t');
expect(getByText('Lifecycle')).toBeInTheDocument();
expect(getByText('Lifecycle').nextSibling).toHaveTextContent('l');
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent('user:o');
expect(screen.getByText('Domain')).toBeInTheDocument();
expect(screen.getByText('Domain').nextSibling).toHaveTextContent('d');
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent('s');
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('t');
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle').nextSibling).toHaveTextContent('l');
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
@@ -95,26 +93,25 @@ describe('<AboutContent />', () => {
entity.spec = {};
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(queryByText('Type')).not.toBeInTheDocument();
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.queryByText('Type')).not.toBeInTheDocument();
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
});
});
@@ -151,33 +148,34 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('system');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('openapi');
expect(getByText('Lifecycle')).toBeInTheDocument();
expect(getByText('Lifecycle').nextSibling).toHaveTextContent(
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'user:guest',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'system',
);
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('openapi');
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle').nextSibling).toHaveTextContent(
'production',
);
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
@@ -187,31 +185,34 @@ describe('<AboutContent />', () => {
delete entity.spec!.system;
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('No System');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(getByText('Lifecycle')).toBeInTheDocument();
expect(getByText('Lifecycle').nextSibling).toHaveTextContent('unknown');
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'No System',
);
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle').nextSibling).toHaveTextContent(
'unknown',
);
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
@@ -252,36 +253,37 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('system');
expect(getByText('Parent Component')).toBeInTheDocument();
expect(getByText('Parent Component').nextSibling).toHaveTextContent(
'parent-software',
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'user:guest',
);
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('service');
expect(getByText('Lifecycle')).toBeInTheDocument();
expect(getByText('Lifecycle').nextSibling).toHaveTextContent(
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'system',
);
expect(screen.getByText('Parent Component')).toBeInTheDocument();
expect(
screen.getByText('Parent Component').nextSibling,
).toHaveTextContent('parent-software');
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('service');
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle').nextSibling).toHaveTextContent(
'production',
);
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
@@ -291,31 +293,34 @@ describe('<AboutContent />', () => {
delete entity.spec!.system;
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('No System');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(getByText('Lifecycle')).toBeInTheDocument();
expect(getByText('Lifecycle').nextSibling).toHaveTextContent('unknown');
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'No System',
);
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(screen.getByText('Lifecycle')).toBeInTheDocument();
expect(screen.getByText('Lifecycle').nextSibling).toHaveTextContent(
'unknown',
);
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
@@ -344,56 +349,54 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(queryByText('Type')).not.toBeInTheDocument();
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'user:guest',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.queryByText('Type')).not.toBeInTheDocument();
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
delete entity.metadata.tags;
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(queryByText('Type')).not.toBeInTheDocument();
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.queryByText('Type')).not.toBeInTheDocument();
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
@@ -418,31 +421,30 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('root');
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(getByText('Targets')).toBeInTheDocument();
expect(getByText('Targets').nextSibling).toHaveTextContent(
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('root');
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Targets')).toBeInTheDocument();
expect(screen.getByText('Targets').nextSibling).toHaveTextContent(
'https://backstage.io',
);
});
@@ -451,29 +453,28 @@ describe('<AboutContent />', () => {
delete entity.metadata.tags;
delete entity.spec!.type;
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
@@ -508,30 +509,31 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('system');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('s3');
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'user:guest',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'system',
);
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('s3');
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
@@ -540,30 +542,31 @@ describe('<AboutContent />', () => {
delete entity.spec!.system;
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(queryByText('Domain')).not.toBeInTheDocument();
expect(getByText('System')).toBeInTheDocument();
expect(getByText('System').nextSibling).toHaveTextContent('No System');
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(getByText('Type')).toBeInTheDocument();
expect(getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.queryByText('Domain')).not.toBeInTheDocument();
expect(screen.getByText('System')).toBeInTheDocument();
expect(screen.getByText('System').nextSibling).toHaveTextContent(
'No System',
);
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.getByText('Type')).toBeInTheDocument();
expect(screen.getByText('Type').nextSibling).toHaveTextContent('unknown');
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
@@ -597,29 +600,30 @@ describe('<AboutContent />', () => {
});
it('renders info', async () => {
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest');
expect(getByText('Domain')).toBeInTheDocument();
expect(getByText('Domain').nextSibling).toHaveTextContent('domain');
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(queryByText('Type')).not.toBeInTheDocument();
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'user:guest',
);
expect(screen.getByText('Domain')).toBeInTheDocument();
expect(screen.getByText('Domain').nextSibling).toHaveTextContent(
'domain',
);
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.queryByText('Type')).not.toBeInTheDocument();
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('tag-1');
});
it('highlights missing required fields', async () => {
@@ -627,29 +631,30 @@ describe('<AboutContent />', () => {
delete entity.spec!.domain;
entity.relations = [];
const { getByText, queryByText } = await renderInTestApp(
<AboutContent entity={entity} />,
{
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
await renderInTestApp(<AboutContent entity={entity} />, {
mountedRoutes: {
'/catalog/:namespace/:kind/:name': entityRouteRef,
},
);
});
expect(getByText('Description')).toBeInTheDocument();
expect(getByText('Description').nextSibling).toHaveTextContent(
expect(screen.getByText('Description')).toBeInTheDocument();
expect(screen.getByText('Description').nextSibling).toHaveTextContent(
'This is the description',
);
expect(getByText('Owner')).toBeInTheDocument();
expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner');
expect(getByText('Domain')).toBeInTheDocument();
expect(getByText('Domain').nextSibling).toHaveTextContent('No Domain');
expect(queryByText('System')).not.toBeInTheDocument();
expect(queryByText('Parent Component')).not.toBeInTheDocument();
expect(queryByText('Type')).not.toBeInTheDocument();
expect(queryByText('Lifecycle')).not.toBeInTheDocument();
expect(getByText('Tags')).toBeInTheDocument();
expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags');
expect(screen.getByText('Owner')).toBeInTheDocument();
expect(screen.getByText('Owner').nextSibling).toHaveTextContent(
'No Owner',
);
expect(screen.getByText('Domain')).toBeInTheDocument();
expect(screen.getByText('Domain').nextSibling).toHaveTextContent(
'No Domain',
);
expect(screen.queryByText('System')).not.toBeInTheDocument();
expect(screen.queryByText('Parent Component')).not.toBeInTheDocument();
expect(screen.queryByText('Type')).not.toBeInTheDocument();
expect(screen.queryByText('Lifecycle')).not.toBeInTheDocument();
expect(screen.getByText('Tags')).toBeInTheDocument();
expect(screen.getByText('Tags').nextSibling).toHaveTextContent('No Tags');
});
});
});
@@ -15,7 +15,7 @@
*/
import React from 'react';
import { fireEvent } from '@testing-library/react';
import { fireEvent, screen } from '@testing-library/react';
import { GetEntityFacetsResponse } from '@backstage/catalog-client';
import { Entity } from '@backstage/catalog-model';
import {
@@ -31,6 +31,7 @@ import {
} from '@backstage/test-utils';
import { CatalogKindHeader } from './CatalogKindHeader';
import { errorApiRef } from '@backstage/core-plugin-api';
import pluralize from 'pluralize';
const entities: Entity[] = [
{
@@ -83,7 +84,7 @@ const apis = TestApiRegistry.from(
describe('<CatalogKindHeader />', () => {
it('renders available kinds', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider>
<CatalogKindHeader />
@@ -91,18 +92,18 @@ describe('<CatalogKindHeader />', () => {
</ApiProvider>,
);
const input = rendered.getByText('Components');
const input = screen.getByText('Components');
fireEvent.mouseDown(input);
entities.map(entity => {
expect(
rendered.getByRole('option', { name: `${entity.kind}s` }),
screen.getByRole('option', { name: `${pluralize(entity.kind)}` }),
).toBeInTheDocument();
});
});
it('renders unknown kinds provided in query parameters', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{ queryParameters: { kind: 'frob' } }}
@@ -112,12 +113,12 @@ describe('<CatalogKindHeader />', () => {
</ApiProvider>,
);
expect(rendered.getByText('Frobs')).toBeInTheDocument();
expect(screen.getByText('Frobs')).toBeInTheDocument();
});
it('updates the kind filter', async () => {
const updateFilters = jest.fn();
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider value={{ updateFilters }}>
<CatalogKindHeader />
@@ -125,10 +126,10 @@ describe('<CatalogKindHeader />', () => {
</ApiProvider>,
);
const input = rendered.getByText('Components');
const input = screen.getByText('Components');
fireEvent.mouseDown(input);
const option = rendered.getByRole('option', { name: 'Templates' });
const option = screen.getByRole('option', { name: 'Templates' });
fireEvent.click(option);
expect(updateFilters).toHaveBeenCalledWith({
@@ -171,7 +172,7 @@ describe('<CatalogKindHeader />', () => {
});
it('limits kinds when allowedKinds is set', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider>
<CatalogKindHeader allowedKinds={['component', 'system']} />
@@ -179,22 +180,20 @@ describe('<CatalogKindHeader />', () => {
</ApiProvider>,
);
const input = rendered.getByText('Components');
const input = screen.getByText('Components');
fireEvent.mouseDown(input);
expect(
rendered.getByRole('option', { name: 'Components' }),
screen.getByRole('option', { name: 'Components' }),
).toBeInTheDocument();
expect(screen.getByRole('option', { name: 'Systems' })).toBeInTheDocument();
expect(
rendered.getByRole('option', { name: 'Systems' }),
).toBeInTheDocument();
expect(
rendered.queryByRole('option', { name: 'Templates' }),
screen.queryByRole('option', { name: 'Templates' }),
).not.toBeInTheDocument();
});
it('renders kind from the query parameter even when not in allowedKinds', async () => {
const rendered = await renderWithEffects(
await renderWithEffects(
<ApiProvider apis={apis}>
<MockEntityListContextProvider
value={{ queryParameters: { kind: 'Frob' } }}
@@ -204,12 +203,10 @@ describe('<CatalogKindHeader />', () => {
</ApiProvider>,
);
expect(rendered.getByText('Frobs')).toBeInTheDocument();
const input = rendered.getByText('Frobs');
expect(screen.getByText('Frobs')).toBeInTheDocument();
const input = screen.getByText('Frobs');
fireEvent.mouseDown(input);
expect(
rendered.getByRole('option', { name: 'Systems' }),
).toBeInTheDocument();
expect(screen.getByRole('option', { name: 'Systems' })).toBeInTheDocument();
});
});
@@ -31,6 +31,7 @@ import {
} from '@backstage/plugin-catalog-react';
import useAsync from 'react-use/lib/useAsync';
import { useApi } from '@backstage/core-plugin-api';
import pluralize from 'pluralize';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
@@ -132,7 +133,7 @@ export function CatalogKindHeader(props: CatalogKindHeaderProps) {
>
{Object.keys(options).map(kind => (
<MenuItem value={kind} key={kind}>
{`${options[kind]}s`}
{`${pluralize(options[kind])}`}
</MenuItem>
))}
</Select>
@@ -16,6 +16,7 @@
import React from 'react';
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import { useOutlet } from 'react-router';
import { CatalogPage } from './CatalogPage';
@@ -30,15 +31,15 @@ jest.mock('./DefaultCatalogPage', () => ({
describe('CatalogPage', () => {
it('renders provided router element', async () => {
const { getByText } = await renderInTestApp(<CatalogPage />);
await renderInTestApp(<CatalogPage />);
expect(getByText('Route Children')).toBeInTheDocument();
expect(screen.getByText('Route Children')).toBeInTheDocument();
});
it('renders DefaultCatalogPage home when no router children are provided', async () => {
(useOutlet as jest.Mock).mockReturnValueOnce(null);
const { getByText } = await renderInTestApp(<CatalogPage />);
await renderInTestApp(<CatalogPage />);
expect(getByText('DefaultCatalogPage')).toBeInTheDocument();
expect(screen.getByText('DefaultCatalogPage')).toBeInTheDocument();
});
});
@@ -178,11 +178,11 @@ describe('DefaultCatalogPage', () => {
// limit. We should investigate why these timeouts happen.
it('should render the default column of the grid', async () => {
const { getAllByRole } = await renderWrapped(<DefaultCatalogPage />);
await renderWrapped(<DefaultCatalogPage />);
const columnHeader = getAllByRole('button').filter(
c => c.tagName === 'SPAN',
);
const columnHeader = screen
.getAllByRole('button')
.filter(c => c.tagName === 'SPAN');
const columnHeaderLabels = columnHeader.map(c => c.textContent);
expect(columnHeaderLabels).toEqual([
@@ -203,26 +203,22 @@ describe('DefaultCatalogPage', () => {
{ title: 'Bar', field: 'entity.bar' },
{ title: 'Baz', field: 'entity.spec.lifecycle' },
];
const { getAllByRole } = await renderWrapped(
<DefaultCatalogPage columns={columns} />,
);
await renderWrapped(<DefaultCatalogPage columns={columns} />);
const columnHeader = getAllByRole('button').filter(
c => c.tagName === 'SPAN',
);
const columnHeader = screen
.getAllByRole('button')
.filter(c => c.tagName === 'SPAN');
const columnHeaderLabels = columnHeader.map(c => c.textContent);
expect(columnHeaderLabels).toEqual(['Foo', 'Bar', 'Baz', 'Actions']);
}, 20_000);
it('should render the default actions of an item in the grid', async () => {
const { getByTestId, findByTitle, findByText } = await renderWrapped(
<DefaultCatalogPage />,
);
fireEvent.click(getByTestId('user-picker-owned'));
expect(await findByText(/Owned \(1\)/)).toBeInTheDocument();
expect(await findByTitle(/View/)).toBeInTheDocument();
expect(await findByTitle(/Edit/)).toBeInTheDocument();
expect(await findByTitle(/Add to favorites/)).toBeInTheDocument();
await renderWrapped(<DefaultCatalogPage />);
fireEvent.click(screen.getByTestId('user-picker-owned'));
expect(await screen.findByText(/Owned \(1\)/)).toBeInTheDocument();
expect(await screen.findByTitle(/View/)).toBeInTheDocument();
expect(await screen.findByTitle(/Edit/)).toBeInTheDocument();
expect(await screen.findByTitle(/Add to favorites/)).toBeInTheDocument();
}, 20_000);
it('should render the custom actions of an item passed as prop', async () => {
@@ -245,41 +241,35 @@ describe('DefaultCatalogPage', () => {
},
];
const { getByTestId, findByTitle, findByText } = await renderWrapped(
<DefaultCatalogPage actions={actions} />,
);
fireEvent.click(getByTestId('user-picker-owned'));
expect(await findByText(/Owned \(1\)/)).toBeInTheDocument();
expect(await findByTitle(/Foo Action/)).toBeInTheDocument();
expect(await findByTitle(/Bar Action/)).toBeInTheDocument();
expect((await findByTitle(/Bar Action/)).firstChild).toBeDisabled();
await renderWrapped(<DefaultCatalogPage actions={actions} />);
fireEvent.click(screen.getByTestId('user-picker-owned'));
expect(await screen.findByText(/Owned \(1\)/)).toBeInTheDocument();
expect(await screen.findByTitle(/Foo Action/)).toBeInTheDocument();
expect(await screen.findByTitle(/Bar Action/)).toBeInTheDocument();
expect((await screen.findByTitle(/Bar Action/)).firstChild).toBeDisabled();
}, 20_000);
// this test right now causes some red lines in the log output when running tests
// related to some theme issues in mui-table
// https://github.com/mbrn/material-table/issues/1293
it('should render', async () => {
const { findByText, getByTestId } = await renderWrapped(
<DefaultCatalogPage />,
);
fireEvent.click(getByTestId('user-picker-owned'));
await expect(findByText(/Owned \(1\)/)).resolves.toBeInTheDocument();
fireEvent.click(getByTestId('user-picker-all'));
await expect(findByText(/All \(2\)/)).resolves.toBeInTheDocument();
await renderWrapped(<DefaultCatalogPage />);
fireEvent.click(screen.getByTestId('user-picker-owned'));
await expect(screen.findByText(/Owned \(1\)/)).resolves.toBeInTheDocument();
fireEvent.click(screen.getByTestId('user-picker-all'));
await expect(screen.findByText(/All \(2\)/)).resolves.toBeInTheDocument();
}, 20_000);
it('should set initial filter correctly', async () => {
const { findByText } = await renderWrapped(
<DefaultCatalogPage initiallySelectedFilter="all" />,
);
await expect(findByText(/All \(2\)/)).resolves.toBeInTheDocument();
await renderWrapped(<DefaultCatalogPage initiallySelectedFilter="all" />);
await expect(screen.findByText(/All \(2\)/)).resolves.toBeInTheDocument();
}, 20_000);
// this test is for fixing the bug after favoriting an entity, the matching
// entities defaulting to "owned" filter and not based on the selected filter
it('should render the correct entities filtered on the selected filter', async () => {
const { getByTestId } = await renderWrapped(<DefaultCatalogPage />);
fireEvent.click(getByTestId('user-picker-owned'));
await renderWrapped(<DefaultCatalogPage />);
fireEvent.click(screen.getByTestId('user-picker-owned'));
await expect(screen.findByText(/Owned \(1\)/)).resolves.toBeInTheDocument();
// The "Starred" menu option should initially be disabled, since there
// aren't any starred entities.
@@ -308,10 +298,12 @@ describe('DefaultCatalogPage', () => {
it('should wrap filter in drawer on smaller screens', async () => {
mockBreakpoint({ matches: true });
const { getByRole } = await renderWrapped(<DefaultCatalogPage />);
const button = getByRole('button', { name: 'Filters' });
expect(getByRole('presentation', { hidden: true })).toBeInTheDocument();
await renderWrapped(<DefaultCatalogPage />);
const button = screen.getByRole('button', { name: 'Filters' });
expect(
screen.getByRole('presentation', { hidden: true }),
).toBeInTheDocument();
fireEvent.click(button);
expect(getByRole('presentation')).toBeVisible();
expect(screen.getByRole('presentation')).toBeVisible();
}, 20_000);
});
@@ -29,7 +29,7 @@ import {
UserListFilter,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiRegistry } from '@backstage/test-utils';
import { act, fireEvent } from '@testing-library/react';
import { act, fireEvent, screen } from '@testing-library/react';
import * as React from 'react';
import { CatalogTable } from './CatalogTable';
@@ -66,7 +66,7 @@ describe('CatalogTable component', () => {
});
it('should render error message', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider value={{ error: new Error('error') }}>
<CatalogTable />
@@ -78,14 +78,14 @@ describe('CatalogTable component', () => {
},
},
);
const errorMessage = await rendered.findByText(
const errorMessage = await screen.findByText(
/Could not fetch catalog entities./,
);
expect(errorMessage).toBeInTheDocument();
});
it('should display entity names when loading has finished and no error occurred', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider
value={{
@@ -108,10 +108,10 @@ describe('CatalogTable component', () => {
},
},
);
expect(rendered.getByText(/Owned \(3\)/)).toBeInTheDocument();
expect(rendered.getByText(/component1/)).toBeInTheDocument();
expect(rendered.getByText(/component2/)).toBeInTheDocument();
expect(rendered.getByText(/component3/)).toBeInTheDocument();
expect(screen.getByText(/Owned \(3\)/)).toBeInTheDocument();
expect(screen.getByText(/component1/)).toBeInTheDocument();
expect(screen.getByText(/component2/)).toBeInTheDocument();
expect(screen.getByText(/component3/)).toBeInTheDocument();
});
it('should use specified edit URL if in annotation', async () => {
@@ -124,7 +124,7 @@ describe('CatalogTable component', () => {
},
};
const { getByTitle } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider value={{ entities: [entity] }}>
<CatalogTable />
@@ -137,7 +137,7 @@ describe('CatalogTable component', () => {
},
);
const editButton = getByTitle('Edit');
const editButton = screen.getByTitle('Edit');
await act(async () => {
fireEvent.click(editButton);
@@ -156,7 +156,7 @@ describe('CatalogTable component', () => {
},
};
const { getByTitle } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider value={{ entities: [entity] }}>
<CatalogTable />
@@ -169,7 +169,7 @@ describe('CatalogTable component', () => {
},
);
const viewButton = getByTitle('View');
const viewButton = screen.getByTitle('View');
await act(async () => {
fireEvent.click(viewButton);
@@ -278,7 +278,7 @@ describe('CatalogTable component', () => {
])(
'should render correct columns with kind filter $kind',
async ({ kind, expectedColumns }) => {
const { getAllByRole } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider
value={{
@@ -298,9 +298,9 @@ describe('CatalogTable component', () => {
},
);
const columnHeader = getAllByRole('button').filter(
c => c.tagName === 'SPAN',
);
const columnHeader = screen
.getAllByRole('button')
.filter(c => c.tagName === 'SPAN');
const columnHeaderLabels = columnHeader.map(c => c.textContent);
expect(columnHeaderLabels).toEqual(expectedColumns);
},
@@ -316,7 +316,7 @@ describe('CatalogTable component', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider value={{ entities: [entity] }}>
<CatalogTable subtitle="Should be rendered" />
@@ -329,7 +329,7 @@ describe('CatalogTable component', () => {
},
);
expect(getByText('Should be rendered')).toBeInTheDocument();
expect(screen.getByText('Should be rendered')).toBeInTheDocument();
});
it('should render the label column with customised title and value as specified', async () => {
@@ -347,7 +347,7 @@ describe('CatalogTable component', () => {
};
const expectedColumns = ['Name', 'Category', 'Actions'];
const { getAllByRole, getByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<MockEntityListContextProvider value={{ entities: [entity] }}>
<CatalogTable columns={columns} />
@@ -360,13 +360,13 @@ describe('CatalogTable component', () => {
},
);
const columnHeader = getAllByRole('button').filter(
c => c.tagName === 'SPAN',
);
const columnHeader = screen
.getAllByRole('button')
.filter(c => c.tagName === 'SPAN');
const columnHeaderLabels = columnHeader.map(c => c.textContent);
expect(columnHeaderLabels).toEqual(expectedColumns);
const labelCellValue = getByText('generic');
const labelCellValue = screen.getByText('generic');
expect(labelCellValue).toBeInTheDocument();
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { screen, waitFor } from '@testing-library/react';
import React from 'react';
import { DependencyOfComponentsCard } from './DependencyOfComponentsCard';
@@ -51,7 +51,7 @@ describe('<DependencyOfComponentsCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependencyOfComponentsCard />
@@ -64,9 +64,9 @@ describe('<DependencyOfComponentsCard />', () => {
},
);
expect(getByText('Dependency of components')).toBeInTheDocument();
expect(screen.getByText('Dependency of components')).toBeInTheDocument();
expect(
getByText(/No component depends on this component/i),
screen.getByText(/No component depends on this component/i),
).toBeInTheDocument();
});
@@ -99,7 +99,7 @@ describe('<DependencyOfComponentsCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependencyOfComponentsCard />
@@ -113,8 +113,8 @@ describe('<DependencyOfComponentsCard />', () => {
);
await waitFor(() => {
expect(getByText('Dependency of components')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Dependency of components')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { DependsOnComponentsCard } from './DependsOnComponentsCard';
@@ -51,7 +51,7 @@ describe('<DependsOnComponentsCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependsOnComponentsCard />
@@ -64,9 +64,9 @@ describe('<DependsOnComponentsCard />', () => {
},
);
expect(getByText('Depends on components')).toBeInTheDocument();
expect(screen.getByText('Depends on components')).toBeInTheDocument();
expect(
getByText(/No component is a dependency of this component/i),
screen.getByText(/No component is a dependency of this component/i),
).toBeInTheDocument();
});
@@ -99,7 +99,7 @@ describe('<DependsOnComponentsCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependsOnComponentsCard />
@@ -113,8 +113,8 @@ describe('<DependsOnComponentsCard />', () => {
);
await waitFor(() => {
expect(getByText('Depends on components')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Depends on components')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { DependsOnResourcesCard } from './DependsOnResourcesCard';
@@ -51,7 +51,7 @@ describe('<DependsOnResourcesCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependsOnResourcesCard />
@@ -64,9 +64,9 @@ describe('<DependsOnResourcesCard />', () => {
},
);
expect(getByText('Depends on resources')).toBeInTheDocument();
expect(screen.getByText('Depends on resources')).toBeInTheDocument();
expect(
getByText(/No resource is a dependency of this component/i),
screen.getByText(/No resource is a dependency of this component/i),
).toBeInTheDocument();
});
@@ -99,7 +99,7 @@ describe('<DependsOnResourcesCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<DependsOnResourcesCard />
@@ -113,8 +113,8 @@ describe('<DependsOnResourcesCard />', () => {
);
await waitFor(() => {
expect(getByText('Depends on resources')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Depends on resources')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -63,7 +63,7 @@ describe('ComponentContextMenu', () => {
it('check Unregister entity button is disabled', async () => {
const mockCallback = jest.fn();
const { getByText } = await render(
await render(
<EntityContextMenu
UNSTABLE_contextMenuOptions={{ disableUnregister: 'disable' }}
onUnregisterEntity={mockCallback}
@@ -75,10 +75,10 @@ describe('ComponentContextMenu', () => {
expect(button).toBeInTheDocument();
fireEvent.click(button);
const unregister = await screen.getByText('Unregister entity');
const unregister = screen.getByText('Unregister entity');
expect(unregister).toBeInTheDocument();
const unregisterSpanItem = getByText(/Unregister entity/);
const unregisterSpanItem = screen.getByText(/Unregister entity/);
const unregisterMenuListItem =
unregisterSpanItem?.parentElement?.parentElement;
expect(unregisterMenuListItem).toHaveAttribute('aria-disabled');
@@ -60,7 +60,7 @@ describe('ComponentContextMenu', () => {
it('check Unregister entity button is disabled', async () => {
const mockCallback = jest.fn();
const { getByText } = await render(
await render(
<UnregisterEntity
unregisterEntityOptions={{ disableUnregister: 'disable' }}
isUnregisterAllowed
@@ -69,10 +69,10 @@ describe('ComponentContextMenu', () => {
/>,
);
const unregister = await screen.getByText('Unregister entity');
const unregister = screen.getByText('Unregister entity');
expect(unregister).toBeInTheDocument();
const unregisterSpanItem = getByText(/Unregister entity/);
const unregisterSpanItem = screen.getByText(/Unregister entity/);
const unregisterMenuListItem =
unregisterSpanItem?.parentElement?.parentElement;
expect(unregisterMenuListItem).toHaveAttribute('aria-disabled');
@@ -32,7 +32,7 @@ import {
renderInTestApp,
TestApiRegistry,
} from '@backstage/test-utils';
import { act, fireEvent } from '@testing-library/react';
import { act, fireEvent, screen } from '@testing-library/react';
import React from 'react';
import { EntityLayout } from './EntityLayout';
@@ -52,7 +52,7 @@ const mockApis = TestApiRegistry.from(
describe('EntityLayout', () => {
it('renders simplest case', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<EntityProvider entity={mockEntity}>
<EntityLayout>
@@ -69,9 +69,9 @@ describe('EntityLayout', () => {
},
);
expect(rendered.getByText('my-entity')).toBeInTheDocument();
expect(rendered.getByText('tabbed-test-title')).toBeInTheDocument();
expect(rendered.getByText('tabbed-test-content')).toBeInTheDocument();
expect(screen.getByText('my-entity')).toBeInTheDocument();
expect(screen.getByText('tabbed-test-title')).toBeInTheDocument();
expect(screen.getByText('tabbed-test-content')).toBeInTheDocument();
});
it('renders the entity title if defined', async () => {
@@ -83,7 +83,7 @@ describe('EntityLayout', () => {
},
} as Entity;
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<EntityProvider entity={mockEntityWithTitle}>
<EntityLayout>
@@ -100,13 +100,13 @@ describe('EntityLayout', () => {
},
);
expect(rendered.getByText('My Entity')).toBeInTheDocument();
expect(rendered.getByText('tabbed-test-title')).toBeInTheDocument();
expect(rendered.getByText('tabbed-test-content')).toBeInTheDocument();
expect(screen.getByText('My Entity')).toBeInTheDocument();
expect(screen.getByText('tabbed-test-title')).toBeInTheDocument();
expect(screen.getByText('tabbed-test-content')).toBeInTheDocument();
});
it('renders default error message when entity is not found', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<AsyncEntityProvider loading={false}>
<EntityLayout>
@@ -123,14 +123,14 @@ describe('EntityLayout', () => {
},
);
expect(rendered.getByText('Warning: Entity not found')).toBeInTheDocument();
expect(rendered.queryByText('my-entity')).not.toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-title')).not.toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-content')).not.toBeInTheDocument();
expect(screen.getByText('Warning: Entity not found')).toBeInTheDocument();
expect(screen.queryByText('my-entity')).not.toBeInTheDocument();
expect(screen.queryByText('tabbed-test-title')).not.toBeInTheDocument();
expect(screen.queryByText('tabbed-test-content')).not.toBeInTheDocument();
});
it('renders custom message when entity is not found', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<AsyncEntityProvider loading={false}>
<EntityLayout
@@ -150,15 +150,15 @@ describe('EntityLayout', () => {
);
expect(
rendered.getByText('Oppps.. Your entity was not found'),
screen.getByText('Oppps.. Your entity was not found'),
).toBeInTheDocument();
expect(rendered.queryByText('my-entity')).not.toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-title')).not.toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-content')).not.toBeInTheDocument();
expect(screen.queryByText('my-entity')).not.toBeInTheDocument();
expect(screen.queryByText('tabbed-test-title')).not.toBeInTheDocument();
expect(screen.queryByText('tabbed-test-content')).not.toBeInTheDocument();
});
it('navigates when user clicks different tab', async () => {
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<EntityProvider entity={mockEntity}>
<EntityLayout>
@@ -181,23 +181,23 @@ describe('EntityLayout', () => {
},
);
const secondTab = rendered.queryAllByRole('tab')[1];
const secondTab = screen.queryAllByRole('tab')[1];
act(() => {
fireEvent.click(secondTab);
});
expect(rendered.getByText('tabbed-test-title')).toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-content')).not.toBeInTheDocument();
expect(screen.getByText('tabbed-test-title')).toBeInTheDocument();
expect(screen.queryByText('tabbed-test-content')).not.toBeInTheDocument();
expect(rendered.getByText('tabbed-test-title-2')).toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-content-2')).toBeInTheDocument();
expect(screen.getByText('tabbed-test-title-2')).toBeInTheDocument();
expect(screen.queryByText('tabbed-test-content-2')).toBeInTheDocument();
});
it('should conditionally render tabs', async () => {
const shouldRenderTab = (e: Entity) => e.metadata.name === 'my-entity';
const shouldNotRenderTab = (e: Entity) => e.metadata.name === 'some-entity';
const rendered = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={mockApis}>
<EntityProvider entity={mockEntity}>
<EntityLayout>
@@ -228,8 +228,8 @@ describe('EntityLayout', () => {
},
);
expect(rendered.queryByText('tabbed-test-title')).toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-title-2')).not.toBeInTheDocument();
expect(rendered.queryByText('tabbed-test-title-3')).toBeInTheDocument();
expect(screen.queryByText('tabbed-test-title')).toBeInTheDocument();
expect(screen.queryByText('tabbed-test-title-2')).not.toBeInTheDocument();
expect(screen.queryByText('tabbed-test-title-3')).toBeInTheDocument();
});
});
@@ -17,6 +17,7 @@
import { Entity, EntityLink } from '@backstage/catalog-model';
import { EntityProvider } from '@backstage/plugin-catalog-react';
import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { EntityLinksCard } from './EntityLinksCard';
@@ -43,7 +44,7 @@ describe('EntityLinksCard', () => {
it('should render a link', async () => {
const links: EntityLink[] = [createLink()];
const { queryByText } = await renderWithEffects(
await renderWithEffects(
wrapInTestApp(
<EntityProvider entity={createEntity(links)}>
<EntityLinksCard />
@@ -51,12 +52,12 @@ describe('EntityLinksCard', () => {
),
);
expect(queryByText('admin dashboard')).toBeInTheDocument();
expect(queryByText('derp')).not.toBeInTheDocument();
expect(screen.queryByText('admin dashboard')).toBeInTheDocument();
expect(screen.queryByText('derp')).not.toBeInTheDocument();
});
it('should show empty state', async () => {
const { queryByText } = await renderWithEffects(
await renderWithEffects(
wrapInTestApp(
<EntityProvider entity={createEntity([])}>
<EntityLinksCard />
@@ -65,8 +66,8 @@ describe('EntityLinksCard', () => {
);
expect(
queryByText(/.*No links defined for this entity.*/),
screen.queryByText(/.*No links defined for this entity.*/),
).toBeInTheDocument();
expect(queryByText('admin dashboard')).not.toBeInTheDocument();
expect(screen.queryByText('admin dashboard')).not.toBeInTheDocument();
});
});
@@ -17,13 +17,13 @@
import { lightTheme } from '@backstage/theme';
import { ThemeProvider } from '@material-ui/core';
import CloudIcon from '@material-ui/icons/Cloud';
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import React from 'react';
import { IconLink } from './IconLink';
describe('IconLink', () => {
it('should render an icon link', () => {
const rendered = render(
render(
<ThemeProvider theme={lightTheme}>
<IconLink
href="https://example.com"
@@ -33,6 +33,6 @@ describe('IconLink', () => {
</ThemeProvider>,
);
expect(rendered.queryByText('I am Link')).toBeInTheDocument();
expect(screen.queryByText('I am Link')).toBeInTheDocument();
});
});
@@ -16,13 +16,16 @@
import React from 'react';
import { renderInTestApp } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import { EntityNotFound } from './EntityNotFound';
describe('<EntityNotFound />', () => {
it('renders without exploding', async () => {
const { getByText } = await renderInTestApp(<EntityNotFound />);
expect(getByText(/entity was not found/i)).toBeInTheDocument();
expect(getByText(/getting started documentation/i)).toBeInTheDocument();
expect(getByText(/docs/i)).toBeInTheDocument();
await renderInTestApp(<EntityNotFound />);
expect(screen.getByText(/entity was not found/i)).toBeInTheDocument();
expect(
screen.getByText(/getting started documentation/i),
).toBeInTheDocument();
expect(screen.getByText(/docs/i)).toBeInTheDocument();
});
});
@@ -15,8 +15,8 @@
*/
import { catalogApiRef, EntityProvider } from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { rootRouteRef } from '../../routes';
import { EntityOrphanWarning } from './EntityOrphanWarning';
@@ -39,7 +39,7 @@ describe('<EntityOrphanWarning />', () => {
},
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider
apis={[
[
@@ -61,7 +61,7 @@ describe('<EntityOrphanWarning />', () => {
},
);
expect(
getByText(
screen.getByText(
'This entity is not referenced by any location and is therefore not receiving updates. Click here to delete.',
),
).toBeInTheDocument();
@@ -23,6 +23,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiRegistry } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { EntityProcessingErrorsPanel } from './EntityProcessingErrorsPanel';
@@ -100,7 +101,7 @@ describe('<EntityProcessErrors />', () => {
rootEntityRef: stringifyEntityRef(entity),
items: [{ entity, parentEntityRefs: [] }],
});
const { getByText, queryByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<EntityProvider entity={entity}>
<EntityProcessingErrorsPanel />
@@ -109,14 +110,14 @@ describe('<EntityProcessErrors />', () => {
);
expect(
getByText(
screen.getByText(
'Error: Policy check failed; caused by Error: Malformed envelope, /metadata/labels should be object',
),
).toBeInTheDocument();
expect(getByText('Error: Foo')).toBeInTheDocument();
expect(queryByText('Error: This should not be rendered')).toBeNull();
expect(screen.getByText('Error: Foo')).toBeInTheDocument();
expect(screen.queryByText('Error: This should not be rendered')).toBeNull();
expect(
queryByText('The error below originates from'),
screen.queryByText('The error below originates from'),
).not.toBeInTheDocument();
});
@@ -204,7 +205,7 @@ describe('<EntityProcessErrors />', () => {
{ entity: parent, parentEntityRefs: [] },
],
});
const { getByText, queryByText } = await renderInTestApp(
await renderInTestApp(
<ApiProvider apis={apis}>
<EntityProvider entity={entity}>
<EntityProcessingErrorsPanel />
@@ -218,12 +219,14 @@ describe('<EntityProcessErrors />', () => {
);
expect(
getByText(
screen.getByText(
'Error: Policy check failed; caused by Error: Malformed envelope, /metadata/labels should be object',
),
).toBeInTheDocument();
expect(getByText('Error: Foo')).toBeInTheDocument();
expect(queryByText('Error: This should not be rendered')).toBeNull();
expect(queryByText('The error below originates from')).toBeInTheDocument();
expect(screen.getByText('Error: Foo')).toBeInTheDocument();
expect(screen.queryByText('Error: This should not be rendered')).toBeNull();
expect(
screen.queryByText('The error below originates from'),
).toBeInTheDocument();
});
});
@@ -19,7 +19,7 @@ import {
AsyncEntityProvider,
EntityProvider,
} from '@backstage/plugin-catalog-react';
import { render } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import React from 'react';
import { isKind } from './conditions';
import { EntitySwitch } from './EntitySwitch';
@@ -54,9 +54,9 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(rendered.queryByText('C')).not.toBeInTheDocument();
expect(screen.queryByText('A')).toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).not.toBeInTheDocument();
rendered.rerender(
<Wrapper>
@@ -68,9 +68,9 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).toBeInTheDocument();
expect(rendered.queryByText('C')).not.toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).toBeInTheDocument();
expect(screen.queryByText('C')).not.toBeInTheDocument();
rendered.rerender(
<Wrapper>
@@ -82,9 +82,9 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(rendered.queryByText('C')).toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).toBeInTheDocument();
rendered.rerender(
<Wrapper>
@@ -94,9 +94,9 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(rendered.queryByText('C')).toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('C')).toBeInTheDocument();
});
it('should switch child when filters switch', () => {
@@ -113,8 +113,8 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
expect(screen.queryByText('A')).toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
rendered.rerender(
<Wrapper>
@@ -127,15 +127,15 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).toBeInTheDocument();
});
it('should switch with async condition that is true', async () => {
const entity = { metadata: { name: 'mock' }, kind: 'component' } as Entity;
const shouldRender = () => Promise.resolve(true);
const rendered = render(
render(
<Wrapper>
<EntityProvider entity={entity}>
<EntitySwitch>
@@ -146,15 +146,15 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
await expect(rendered.findByText('A')).resolves.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
await expect(screen.findByText('A')).resolves.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
});
it('should switch with sync condition that is false', async () => {
const entity = { metadata: { name: 'mock' }, kind: 'component' } as Entity;
const shouldRender = () => Promise.resolve(false);
const rendered = render(
render(
<Wrapper>
<EntityProvider entity={entity}>
<EntitySwitch>
@@ -165,15 +165,15 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
await expect(rendered.findByText('B')).resolves.toBeInTheDocument();
expect(rendered.queryByText('A')).not.toBeInTheDocument();
await expect(screen.findByText('B')).resolves.toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
});
it('should switch with sync condition that throws', async () => {
const entity = { metadata: { name: 'mock' }, kind: 'component' } as Entity;
const shouldRender = () => Promise.reject();
const rendered = render(
render(
<Wrapper>
<EntityProvider entity={entity}>
<EntitySwitch>
@@ -185,8 +185,8 @@ describe('EntitySwitch', () => {
</Wrapper>,
);
await expect(rendered.findByText('C')).resolves.toBeInTheDocument();
expect(rendered.queryByText('A')).not.toBeInTheDocument();
expect(rendered.queryByText('B')).not.toBeInTheDocument();
await expect(screen.findByText('C')).resolves.toBeInTheDocument();
expect(screen.queryByText('A')).not.toBeInTheDocument();
expect(screen.queryByText('B')).not.toBeInTheDocument();
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { HasComponentsCard } from './HasComponentsCard';
@@ -51,7 +51,7 @@ describe('<HasComponentsCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasComponentsCard />
@@ -64,9 +64,9 @@ describe('<HasComponentsCard />', () => {
},
);
expect(getByText('Has components')).toBeInTheDocument();
expect(screen.getByText('Has components')).toBeInTheDocument();
expect(
getByText(/No component is part of this system/i),
screen.getByText(/No component is part of this system/i),
).toBeInTheDocument();
});
@@ -99,7 +99,7 @@ describe('<HasComponentsCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasComponentsCard />
@@ -113,8 +113,8 @@ describe('<HasComponentsCard />', () => {
);
await waitFor(() => {
expect(getByText('Has components')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Has components')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { HasResourcesCard } from './HasResourcesCard';
@@ -51,7 +51,7 @@ describe('<HasResourcesCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasResourcesCard />
@@ -59,9 +59,9 @@ describe('<HasResourcesCard />', () => {
</Wrapper>,
);
expect(getByText('Has resources')).toBeInTheDocument();
expect(screen.getByText('Has resources')).toBeInTheDocument();
expect(
getByText(/No resource is part of this system/i),
screen.getByText(/No resource is part of this system/i),
).toBeInTheDocument();
});
@@ -94,7 +94,7 @@ describe('<HasResourcesCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasResourcesCard />
@@ -108,8 +108,8 @@ describe('<HasResourcesCard />', () => {
);
await waitFor(() => {
expect(getByText('Has resources')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Has resources')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { HasSubcomponentsCard } from './HasSubcomponentsCard';
@@ -51,7 +51,7 @@ describe('<HasSubcomponentsCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasSubcomponentsCard />
@@ -64,9 +64,9 @@ describe('<HasSubcomponentsCard />', () => {
},
);
expect(getByText('Has subcomponents')).toBeInTheDocument();
expect(screen.getByText('Has subcomponents')).toBeInTheDocument();
expect(
getByText(/No subcomponent is part of this component/i),
screen.getByText(/No subcomponent is part of this component/i),
).toBeInTheDocument();
});
@@ -99,7 +99,7 @@ describe('<HasSubcomponentsCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasSubcomponentsCard />
@@ -113,8 +113,8 @@ describe('<HasSubcomponentsCard />', () => {
);
await waitFor(() => {
expect(getByText('Has subcomponents')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Has subcomponents')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,7 +22,7 @@ import {
entityRouteRef,
} from '@backstage/plugin-catalog-react';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { waitFor } from '@testing-library/react';
import { waitFor, screen } from '@testing-library/react';
import React from 'react';
import { HasSystemsCard } from './HasSystemsCard';
@@ -51,7 +51,7 @@ describe('<HasSystemsCard />', () => {
relations: [],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasSystemsCard />
@@ -64,8 +64,10 @@ describe('<HasSystemsCard />', () => {
},
);
expect(getByText('Has systems')).toBeInTheDocument();
expect(getByText(/No system is part of this domain/i)).toBeInTheDocument();
expect(screen.getByText('Has systems')).toBeInTheDocument();
expect(
screen.getByText(/No system is part of this domain/i),
).toBeInTheDocument();
});
it('shows related systems', async () => {
@@ -97,7 +99,7 @@ describe('<HasSystemsCard />', () => {
],
});
const { getByText } = await renderInTestApp(
await renderInTestApp(
<Wrapper>
<EntityProvider entity={entity}>
<HasSystemsCard />
@@ -111,8 +113,8 @@ describe('<HasSystemsCard />', () => {
);
await waitFor(() => {
expect(getByText('Has systems')).toBeInTheDocument();
expect(getByText(/target-name/i)).toBeInTheDocument();
expect(screen.getByText('Has systems')).toBeInTheDocument();
expect(screen.getByText(/target-name/i)).toBeInTheDocument();
});
});
});
@@ -22,6 +22,7 @@ import {
} from '@backstage/plugin-catalog-react';
import { Entity, RELATION_PART_OF } from '@backstage/catalog-model';
import { renderInTestApp, TestApiProvider } from '@backstage/test-utils';
import { screen } from '@testing-library/react';
import React from 'react';
import { SystemDiagramCard } from './SystemDiagramCard';
@@ -53,7 +54,7 @@ describe('<SystemDiagramCard />', () => {
relations: [],
};
const { queryByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<EntityProvider entity={entity}>
<SystemDiagramCard />
@@ -66,9 +67,9 @@ describe('<SystemDiagramCard />', () => {
},
);
expect(queryByText(/System Diagram/)).toBeInTheDocument();
expect(queryByText(/namespace2\/system2/)).toBeInTheDocument();
expect(queryByText(/namespace\/entity/)).not.toBeInTheDocument();
expect(screen.queryByText(/System Diagram/)).toBeInTheDocument();
expect(screen.queryByText(/namespace2\/system2/)).toBeInTheDocument();
expect(screen.queryByText(/namespace\/entity/)).not.toBeInTheDocument();
});
it('shows related systems', async () => {
@@ -108,7 +109,7 @@ describe('<SystemDiagramCard />', () => {
],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<EntityProvider entity={entity}>
<SystemDiagramCard />
@@ -121,9 +122,9 @@ describe('<SystemDiagramCard />', () => {
},
);
expect(getByText('System Diagram')).toBeInTheDocument();
expect(getByText('namespace/system')).toBeInTheDocument();
expect(getByText('namespace/entity')).toBeInTheDocument();
expect(screen.getByText('System Diagram')).toBeInTheDocument();
expect(screen.getByText('namespace/system')).toBeInTheDocument();
expect(screen.getByText('namespace/entity')).toBeInTheDocument();
});
it('should truncate long domains, systems or entities', async () => {
@@ -163,7 +164,7 @@ describe('<SystemDiagramCard />', () => {
],
};
const { getByText } = await renderInTestApp(
await renderInTestApp(
<TestApiProvider apis={[[catalogApiRef, catalogApi]]}>
<EntityProvider entity={entity}>
<SystemDiagramCard />
@@ -176,8 +177,8 @@ describe('<SystemDiagramCard />', () => {
},
);
expect(getByText('namespace/alongdomai...')).toBeInTheDocument();
expect(getByText('namespace/alongsyste...')).toBeInTheDocument();
expect(getByText('namespace/alongentit...')).toBeInTheDocument();
expect(screen.getByText('namespace/alongdomai...')).toBeInTheDocument();
expect(screen.getByText('namespace/alongsyste...')).toBeInTheDocument();
expect(screen.getByText('namespace/alongentit...')).toBeInTheDocument();
});
});
+1 -1
View File
@@ -30,7 +30,7 @@
"@material-ui/core": "^4.9.10",
"@material-ui/icons": "^4.9.1",
"@material-ui/lab": "^4.0.0-alpha.57",
"rc-progress": "3.4.0",
"rc-progress": "3.4.1",
"react-use": "^17.2.4"
},
"peerDependencies": {
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { SyntheticsLocation } from './SyntheticsLocation';
import { renderInTestApp, TestApiRegistry } from '@backstage/test-utils';
@@ -60,6 +61,6 @@ describe('SyntheticsLocation', () => {
</ApiProvider>,
);
expect(await rendered.findByText(/__location__/)).toBeInTheDocument();
expect(await rendered.queryByText(/failed/)).not.toBeInTheDocument();
expect(rendered.queryByText(/failed/)).not.toBeInTheDocument();
});
});
+1 -1
View File
@@ -170,8 +170,8 @@ const http = HttpPostIngressEventPublisher.fromConfig({
},
},
logger: env.logger,
router: httpRouter,
});
http.bind(router);
await new EventsBackend(env.logger)
.addPublishers(http)
+2 -1
View File
@@ -33,6 +33,8 @@ export const eventsPlugin: (options?: undefined) => BackendFeature;
// @public
export class HttpPostIngressEventPublisher implements EventPublisher {
// (undocumented)
bind(router: express.Router): void;
// (undocumented)
static fromConfig(env: {
config: Config;
@@ -40,7 +42,6 @@ export class HttpPostIngressEventPublisher implements EventPublisher {
[topic: string]: Omit<HttpPostIngressOptions, 'topic'>;
};
logger: Logger;
router: express.Router;
}): HttpPostIngressEventPublisher;
// (undocumented)
setEventBroker(eventBroker: EventBroker): Promise<void>;
@@ -90,14 +90,11 @@ export const eventsPlugin = createBackendPlugin({
env.registerInit({
deps: {
config: configServiceRef,
httpRouter: httpRouterServiceRef,
logger: loggerServiceRef,
router: httpRouterServiceRef,
},
async init({ config, httpRouter, logger }) {
async init({ config, logger, router }) {
const winstonLogger = loggerToWinstonLogger(logger);
const eventsRouter = Router();
const router = Router();
eventsRouter.use('/http', router);
const ingresses = Object.fromEntries(
extensionPoint.httpPostIngresses.map(ingress => [
@@ -108,23 +105,20 @@ export const eventsPlugin = createBackendPlugin({
const http = HttpPostIngressEventPublisher.fromConfig({
config,
logger: winstonLogger,
router,
ingresses,
logger: winstonLogger,
});
const eventsRouter = Router();
http.bind(eventsRouter);
router.use(eventsRouter);
if (!extensionPoint.eventBroker) {
extensionPoint.setEventBroker(new InMemoryEventBroker(winstonLogger));
}
const eventBroker =
extensionPoint.eventBroker ?? new InMemoryEventBroker(winstonLogger);
extensionPoint.eventBroker!.subscribe(extensionPoint.subscribers);
eventBroker.subscribe(extensionPoint.subscribers);
[extensionPoint.publishers, http]
.flat()
.forEach(publisher =>
publisher.setEventBroker(extensionPoint.eventBroker!),
);
httpRouter.use(eventsRouter);
.forEach(publisher => publisher.setEventBroker(eventBroker));
},
});
},
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { errorHandler, getVoidLogger } from '@backstage/backend-common';
import { getVoidLogger } from '@backstage/backend-common';
import { ConfigReader } from '@backstage/config';
import { TestEventBroker } from '@backstage/plugin-events-backend-test-utils';
import express from 'express';
@@ -35,37 +35,35 @@ describe('HttpPostIngressEventPublisher', () => {
});
const router = Router();
router.use(express.json());
router.use(errorHandler());
const app = express().use(router);
const publisher = HttpPostIngressEventPublisher.fromConfig({
config,
logger,
router,
ingresses: {
testB: {},
},
logger,
});
publisher.bind(router);
const eventBroker = new TestEventBroker();
await publisher.setEventBroker(eventBroker);
const notFoundResponse = await request(app)
.post('/unknown')
.post('/http/unknown')
.timeout(100)
.send({ test: 'data' });
expect(notFoundResponse.status).toBe(404);
const response1 = await request(app)
.post('/testA')
.post('/http/testA')
.set('X-Custom-Header', 'test-value')
.timeout(100)
.send({ testA: 'data' });
expect(response1.status).toBe(202);
const response2 = await request(app)
.post('/testB')
.post('/http/testB')
.set('X-Custom-Header', 'test-value')
.timeout(100)
.send({ testB: 'data' });
@@ -100,14 +98,10 @@ describe('HttpPostIngressEventPublisher', () => {
});
const router = Router();
router.use(express.json());
router.use(errorHandler());
const app = express().use(router);
const publisher = HttpPostIngressEventPublisher.fromConfig({
config,
logger,
router,
ingresses: {
testB: {
validator: async (req, context) => {
@@ -148,26 +142,28 @@ describe('HttpPostIngressEventPublisher', () => {
},
},
},
logger,
});
publisher.bind(router);
const eventBroker = new TestEventBroker();
await publisher.setEventBroker(eventBroker);
const response1 = await request(app)
.post('/testA')
.post('/http/testA')
.timeout(100)
.send({ test: 'data' });
expect(response1.status).toBe(202);
const response2 = await request(app)
.post('/testB')
.post('/http/testB')
.timeout(100)
.send({ test: 'data' });
expect(response2.status).toBe(400);
expect(response2.body).toEqual({ message: 'wrong signature' });
const response3 = await request(app)
.post('/testB')
.post('/http/testB')
.set('X-Test-Signature', 'wrong')
.timeout(100)
.send({ test: 'data' });
@@ -175,21 +171,21 @@ describe('HttpPostIngressEventPublisher', () => {
expect(response3.body).toEqual({ message: 'wrong signature' });
const response4 = await request(app)
.post('/testB')
.post('/http/testB')
.set('X-Test-Signature', 'testB-signature')
.timeout(100)
.send({ test: 'data' });
expect(response4.status).toBe(202);
const response5 = await request(app)
.post('/testC')
.post('/http/testC')
.timeout(100)
.send({ test: 'data' });
expect(response5.status).toBe(404);
expect(response5.body).toEqual({});
const response6 = await request(app)
.post('/testD')
.post('/http/testD')
.timeout(100)
.send({ test: 'data' });
expect(response6.status).toBe(403);
@@ -210,15 +206,10 @@ describe('HttpPostIngressEventPublisher', () => {
it('without configuration', async () => {
const config = new ConfigReader({});
const router = Router();
router.use(express.json());
router.use(errorHandler());
expect(() =>
HttpPostIngressEventPublisher.fromConfig({
config,
logger,
router,
}),
).not.toThrow();
});
@@ -41,7 +41,6 @@ export class HttpPostIngressEventPublisher implements EventPublisher {
config: Config;
ingresses?: { [topic: string]: Omit<HttpPostIngressOptions, 'topic'> };
logger: Logger;
router: express.Router;
}): HttpPostIngressEventPublisher {
const topics =
env.config.getOptionalStringArray('events.http.topics') ?? [];
@@ -55,15 +54,18 @@ export class HttpPostIngressEventPublisher implements EventPublisher {
}
});
return new HttpPostIngressEventPublisher(env.logger, env.router, ingresses);
return new HttpPostIngressEventPublisher(env.logger, ingresses);
}
private constructor(
private logger: Logger,
router: express.Router,
ingresses: { [topic: string]: Omit<HttpPostIngressOptions, 'topic'> },
) {
router.use(this.createRouter(ingresses));
private readonly logger: Logger,
private readonly ingresses: {
[topic: string]: Omit<HttpPostIngressOptions, 'topic'>;
},
) {}
bind(router: express.Router): void {
router.use('/http', this.createRouter(this.ingresses));
}
async setEventBroker(eventBroker: EventBroker): Promise<void> {
@@ -92,8 +94,12 @@ export class HttpPostIngressEventPublisher implements EventPublisher {
const path = `/${topic}`;
router.post(path, async (request, response) => {
const requestDetails = {
body: request.body,
headers: request.headers,
};
const context = new RequestValidationContextImpl();
await validator?.(request, context);
await validator?.(requestDetails, context);
if (context.wasRejected()) {
response
.status(context.rejectionDetails!.status)
+7 -2
View File
@@ -4,7 +4,6 @@
```ts
import { ExtensionPoint } from '@backstage/backend-plugin-api';
import { Request as Request_2 } from 'express';
// @public
export interface EventBroker {
@@ -74,6 +73,12 @@ export interface HttpPostIngressOptions {
validator?: RequestValidator;
}
// @public (undocumented)
export interface RequestDetails {
body: unknown;
headers: Record<string, string | string[] | undefined>;
}
// @public
export interface RequestRejectionDetails {
// (undocumented)
@@ -89,7 +94,7 @@ export interface RequestValidationContext {
// @public
export type RequestValidator = (
request: Request_2,
request: RequestDetails,
context: RequestValidationContext,
) => Promise<void>;
+1 -3
View File
@@ -24,9 +24,7 @@
"postpack": "backstage-cli package postpack"
},
"dependencies": {
"@backstage/backend-plugin-api": "workspace:^",
"@types/express": "^4.17.6",
"express": "^4.17.1"
"@backstage/backend-plugin-api": "workspace:^"
},
"devDependencies": {
"@backstage/cli": "workspace:^"
@@ -0,0 +1,29 @@
/*
* Copyright 2022 The Backstage Authors
*
* 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.
*/
/**
* @public
*/
export interface RequestDetails {
/**
* Request body. JSON payloads have been parsed already.
*/
body: unknown;
/**
* Key-value pairs of header names and values. Header names are lower-cased.
*/
headers: Record<string, string | string[] | undefined>;
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { Request } from 'express';
import { RequestDetails } from './RequestDetails';
import { RequestValidationContext } from './RequestValidationContext';
/**
@@ -29,6 +29,6 @@ import { RequestValidationContext } from './RequestValidationContext';
* @public
*/
export type RequestValidator = (
request: Request,
request: RequestDetails,
context: RequestValidationContext,
) => Promise<void>;

Some files were not shown because too many files have changed in this diff Show More