Merge branch 'master' of github.com:spotify/backstage into blam/react-router
* 'master' of github.com:spotify/backstage: (89 commits) Use URLSearchParams Use location?.type once more chore(catalog): clean up CatalogTable, use only Entity chore(catalog): clean up ComponentPage, use only Entity chore(catalog): tweak getEntityByName a bit, handle 404s properly chore(catalog/star): only set the cache if there are entries from the response chore(catalog/star): added a comment about why we are using a simple cache here chore(catalog/star): removing msw dependency, wrong branch chore(catalog): consistent use of named exports chore(msw): Added msw dependency chore(catalog/star): fixing issues with unmocked deps chore(catalog/star): adding a simple cache to stop flicker as a stopgap chore(catalog/star): reworking how the starring works, it now stores uri sort of references for entities fix(core): Tabs useEffect dependency list docs: format with prettier (#1218) Optional namespace and name as one part of URL docs/auth: added overview, oauth description and glossary docs: added plantuml generation script docs: added prettier config Remove deleted UserBadge component from Sidebar story ...
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"name": "@backstage/test-utils",
|
||||
"description": "Utilities to test Backstage plugins and apps.",
|
||||
"version": "0.1.1-alpha.6",
|
||||
"version": "0.1.1-alpha.7",
|
||||
"private": false,
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
"access": "public",
|
||||
"main": "dist/index.esm.js",
|
||||
"types": "dist/index.d.ts"
|
||||
},
|
||||
"homepage": "https://backstage.io",
|
||||
"repository": {
|
||||
@@ -28,10 +30,10 @@
|
||||
"clean": "backstage-cli clean"
|
||||
},
|
||||
"dependencies": {
|
||||
"@backstage/cli": "^0.1.1-alpha.6",
|
||||
"@backstage/core-api": "^0.1.1-alpha.6",
|
||||
"@backstage/test-utils-core": "^0.1.1-alpha.6",
|
||||
"@backstage/theme": "^0.1.1-alpha.6",
|
||||
"@backstage/cli": "^0.1.1-alpha.7",
|
||||
"@backstage/core-api": "^0.1.1-alpha.7",
|
||||
"@backstage/test-utils-core": "^0.1.1-alpha.7",
|
||||
"@backstage/theme": "^0.1.1-alpha.7",
|
||||
"@material-ui/core": "^4.9.1",
|
||||
"@testing-library/jest-dom": "^5.7.0",
|
||||
"@testing-library/react": "^9.3.2",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { MockErrorApi } from './MockErrorApi';
|
||||
|
||||
async function ifResolved<T>(promise: Promise<T>): Promise<T | 'not-yet'> {
|
||||
return Promise.race([promise, Promise.resolve<'not-yet'>('not-yet')]);
|
||||
}
|
||||
|
||||
describe('MockErrorApi', () => {
|
||||
it('should throw errors by default', () => {
|
||||
const api = new MockErrorApi();
|
||||
expect(() => api.post(new Error('NOPE'))).toThrow(
|
||||
'MockErrorApi received unexpected error, Error: NOPE',
|
||||
);
|
||||
});
|
||||
|
||||
it('should collect errors', () => {
|
||||
const api = new MockErrorApi({ collect: true });
|
||||
|
||||
api.post(new Error('e1'));
|
||||
api.post(new Error('e2'), { hidden: true });
|
||||
api.post(new Error('e3'));
|
||||
|
||||
expect(api.getErrors()).toEqual([
|
||||
{
|
||||
error: new Error('e1'),
|
||||
},
|
||||
{
|
||||
error: new Error('e2'),
|
||||
context: { hidden: true },
|
||||
},
|
||||
{
|
||||
error: new Error('e3'),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('should not emit values', async () => {
|
||||
const api = new MockErrorApi({ collect: true });
|
||||
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
api.error$().subscribe({
|
||||
next({ error }) {
|
||||
reject(error);
|
||||
},
|
||||
error(error) {
|
||||
reject(error);
|
||||
},
|
||||
complete() {
|
||||
reject(new Error('observable was completed'));
|
||||
},
|
||||
});
|
||||
|
||||
setTimeout(() => resolve('timed-out'), 100);
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBe('timed-out');
|
||||
});
|
||||
|
||||
it('should wait for errors', async () => {
|
||||
const api = new MockErrorApi({ collect: true });
|
||||
|
||||
const wait1 = api.waitForError(/1/);
|
||||
const wait2 = api.waitForError(/2/);
|
||||
|
||||
await expect(ifResolved(wait1)).resolves.toBe('not-yet');
|
||||
await expect(ifResolved(wait2)).resolves.toBe('not-yet');
|
||||
api.post(new Error('e0'));
|
||||
await expect(ifResolved(wait1)).resolves.toBe('not-yet');
|
||||
await expect(ifResolved(wait2)).resolves.toBe('not-yet');
|
||||
api.post(new Error('e1'));
|
||||
await expect(ifResolved(wait1)).resolves.toEqual({
|
||||
error: new Error('e1'),
|
||||
});
|
||||
await expect(ifResolved(wait2)).resolves.toBe('not-yet');
|
||||
api.post(new Error('e2'), { hidden: true });
|
||||
await expect(ifResolved(wait2)).resolves.toEqual({
|
||||
error: new Error('e2'),
|
||||
context: { hidden: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('should time out waiting for error', async () => {
|
||||
const api = new MockErrorApi({ collect: true });
|
||||
|
||||
await expect(api.waitForError(/1/, 1)).rejects.toThrow(
|
||||
'Timed out waiting for error',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import {
|
||||
ErrorApi,
|
||||
ErrorContext,
|
||||
errorApiRef,
|
||||
Observable,
|
||||
} from '@backstage/core-api';
|
||||
|
||||
type Options = {
|
||||
collect?: boolean;
|
||||
};
|
||||
|
||||
type ErrorWithContext = {
|
||||
error: Error;
|
||||
context?: ErrorContext;
|
||||
};
|
||||
|
||||
type Waiter = {
|
||||
pattern: RegExp;
|
||||
resolve: (err: ErrorWithContext) => void;
|
||||
};
|
||||
|
||||
const nullObservable = {
|
||||
subscribe: () => ({ unsubscribe: () => {}, closed: true }),
|
||||
};
|
||||
|
||||
export class MockErrorApi implements ErrorApi {
|
||||
static factory = {
|
||||
implements: errorApiRef,
|
||||
deps: {},
|
||||
factory: () => new MockErrorApi(),
|
||||
};
|
||||
|
||||
private readonly errors = new Array<ErrorWithContext>();
|
||||
private readonly waiters = new Set<Waiter>();
|
||||
|
||||
constructor(private readonly options: Options = {}) {}
|
||||
|
||||
post(error: Error, context?: ErrorContext) {
|
||||
if (this.options.collect) {
|
||||
this.errors.push({ error, context });
|
||||
|
||||
for (const waiter of this.waiters) {
|
||||
if (waiter.pattern.test(error.message)) {
|
||||
this.waiters.delete(waiter);
|
||||
waiter.resolve({ error, context });
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(`MockErrorApi received unexpected error, ${error}`);
|
||||
}
|
||||
|
||||
error$(): Observable<{ error: Error; context?: ErrorContext }> {
|
||||
return nullObservable;
|
||||
}
|
||||
|
||||
getErrors(): ErrorWithContext[] {
|
||||
return this.errors;
|
||||
}
|
||||
|
||||
waitForError(
|
||||
pattern: RegExp,
|
||||
timeoutMs: number = 2000,
|
||||
): Promise<ErrorWithContext> {
|
||||
return new Promise<ErrorWithContext>((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new Error('Timed out waiting for error'));
|
||||
}, timeoutMs);
|
||||
|
||||
this.waiters.add({ resolve, pattern });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export { MockErrorApi } from './MockErrorApi';
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from './ErrorApi';
|
||||
@@ -14,22 +14,106 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import React, { FC, useEffect } from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { wrapInTestApp } from './appWrappers';
|
||||
import { wrapInTestApp, renderInTestApp } from './appWrappers';
|
||||
import { Route } from 'react-router';
|
||||
import { withLogCollector } from '@backstage/test-utils-core';
|
||||
import {
|
||||
useApi,
|
||||
errorApiRef,
|
||||
ApiProvider,
|
||||
ApiRegistry,
|
||||
} from '@backstage/core-api';
|
||||
import { MockErrorApi } from './apis';
|
||||
|
||||
describe('wrapInTestApp', () => {
|
||||
it('should provide routing', () => {
|
||||
const rendered = render(
|
||||
wrapInTestApp(
|
||||
<>
|
||||
<Route path="/route1">Route 1</Route>
|
||||
<Route path="/route2">Route 2</Route>
|
||||
</>,
|
||||
{ routeEntries: ['/route2'] },
|
||||
it('should provide routing and warn about missing act()', async () => {
|
||||
const { error } = await withLogCollector(['error'], async () => {
|
||||
const rendered = render(
|
||||
wrapInTestApp(
|
||||
<>
|
||||
<Route path="/route1">Route 1</Route>
|
||||
<Route path="/route2">Route 2</Route>
|
||||
</>,
|
||||
{ routeEntries: ['/route2'] },
|
||||
),
|
||||
);
|
||||
expect(rendered.getByText('Route 2')).toBeInTheDocument();
|
||||
|
||||
// Wait for async actions to trigger the act() warnings that we assert below
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(error).toEqual([
|
||||
expect.stringMatching(
|
||||
/^Warning: An update to %s inside a test was not wrapped in act\(...\)/,
|
||||
),
|
||||
expect.stringMatching(
|
||||
/^Warning: An update to %s inside a test was not wrapped in act\(...\)/,
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should render a component in a test app without warning about missing act()', async () => {
|
||||
const { error } = await withLogCollector(['error'], async () => {
|
||||
const Foo: FC<{}> = () => {
|
||||
return <p>foo</p>;
|
||||
};
|
||||
|
||||
const rendered = await renderInTestApp(Foo);
|
||||
expect(rendered.getByText('foo')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(error).toEqual([]);
|
||||
});
|
||||
|
||||
it('should render a node in a test app', async () => {
|
||||
const Foo: FC<{}> = () => {
|
||||
return <p>foo</p>;
|
||||
};
|
||||
|
||||
const rendered = await renderInTestApp(<Foo />);
|
||||
expect(rendered.getByText('foo')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should provide mock API implementations', async () => {
|
||||
const A: FC<{}> = () => {
|
||||
const errorApi = useApi(errorApiRef);
|
||||
errorApi.post(new Error('NOPE'));
|
||||
return null;
|
||||
};
|
||||
|
||||
const { error } = await withLogCollector(['error'], async () => {
|
||||
await expect(renderInTestApp(A)).rejects.toThrow('NOPE');
|
||||
});
|
||||
|
||||
expect(error).toEqual([
|
||||
expect.stringMatching(
|
||||
/^Error: Uncaught \[Error: MockErrorApi received unexpected error, Error: NOPE\]/,
|
||||
),
|
||||
expect.stringMatching(/^The above error occurred in the <A> component:/),
|
||||
]);
|
||||
});
|
||||
|
||||
it('should allow custom API implementations', async () => {
|
||||
const mockErrorApi = new MockErrorApi({ collect: true });
|
||||
|
||||
const A: FC<{}> = () => {
|
||||
const errorApi = useApi(errorApiRef);
|
||||
useEffect(() => {
|
||||
errorApi.post(new Error('NOPE'));
|
||||
}, [errorApi]);
|
||||
return <p>foo</p>;
|
||||
};
|
||||
|
||||
const rendered = await renderInTestApp(
|
||||
<ApiProvider apis={ApiRegistry.with(errorApiRef, mockErrorApi)}>
|
||||
<A />
|
||||
</ApiProvider>,
|
||||
);
|
||||
expect(rendered.getByText('Route 2')).toBeInTheDocument();
|
||||
|
||||
expect(rendered.getByText('foo')).toBeInTheDocument();
|
||||
expect(mockErrorApi.getErrors()).toEqual([{ error: new Error('NOPE') }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,15 +14,17 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import React, { ComponentType, ReactNode, FunctionComponent, FC } from 'react';
|
||||
import React, { ComponentType, ReactNode, FC, ReactElement } from 'react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { Route } from 'react-router-dom';
|
||||
import { lightTheme } from '@backstage/theme';
|
||||
import privateExports, {
|
||||
defaultSystemIcons,
|
||||
ApiTestRegistry,
|
||||
BootErrorPageProps,
|
||||
} from '@backstage/core-api';
|
||||
import { RenderResult } from '@testing-library/react';
|
||||
import { renderWithEffects } from '@backstage/test-utils-core';
|
||||
import { createMockApiRegistry } from './mockApiRegistry';
|
||||
const { PrivateAppImpl } = privateExports;
|
||||
|
||||
const NotFoundErrorPage = () => {
|
||||
@@ -43,18 +45,29 @@ type TestAppOptions = {
|
||||
routeEntries?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps a component inside a Backstage test app, providing a mocked theme
|
||||
* and app context, along with mocked APIs.
|
||||
*
|
||||
* @param Component - A component or react node to render inside the test app.
|
||||
* @param options - Additional options for the rendering.
|
||||
*/
|
||||
export function wrapInTestApp(
|
||||
Component: ComponentType | ReactNode,
|
||||
options: TestAppOptions = {},
|
||||
) {
|
||||
): ReactElement {
|
||||
const { routeEntries = ['/'] } = options;
|
||||
const apis = createMockApiRegistry();
|
||||
|
||||
const app = new PrivateAppImpl({
|
||||
apis: new ApiTestRegistry(),
|
||||
apis,
|
||||
components: {
|
||||
NotFoundErrorPage,
|
||||
BootErrorPage,
|
||||
Progress,
|
||||
Router: ({ children }) => (
|
||||
<MemoryRouter initialEntries={routeEntries} children={children} />
|
||||
),
|
||||
},
|
||||
icons: defaultSystemIcons,
|
||||
plugins: [],
|
||||
@@ -72,16 +85,31 @@ export function wrapInTestApp(
|
||||
if (Component instanceof Function) {
|
||||
Wrapper = Component;
|
||||
} else {
|
||||
Wrapper = (() => Component) as FunctionComponent;
|
||||
Wrapper = (() => Component) as FC;
|
||||
}
|
||||
|
||||
const AppProvider = app.getProvider();
|
||||
|
||||
return (
|
||||
<AppProvider>
|
||||
<MemoryRouter initialEntries={routeEntries}>
|
||||
<Route element={<Wrapper />} />
|
||||
</MemoryRouter>
|
||||
<Route element={<Wrapper />} />
|
||||
</AppProvider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a component inside a Backstage test app, providing a mocked theme
|
||||
* and app context, along with mocked APIs.
|
||||
*
|
||||
* The render executes async effects similar to `renderWithEffects`. To avoid this
|
||||
* behavior, use a regular `render()` + `wrapInTestApp()` instead.
|
||||
*
|
||||
* @param Component - A component or react node to render inside the test app.
|
||||
* @param options - Additional options for the rendering.
|
||||
*/
|
||||
export async function renderInTestApp(
|
||||
Component: ComponentType | ReactNode,
|
||||
options: TestAppOptions = {},
|
||||
): Promise<RenderResult> {
|
||||
return renderWithEffects(wrapInTestApp(Component, options));
|
||||
}
|
||||
|
||||
@@ -14,5 +14,6 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from './apis';
|
||||
export { default as mockBreakpoint } from './mockBreakpoint';
|
||||
export * from './appWrappers';
|
||||
export { wrapInTestApp, renderInTestApp } from './appWrappers';
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2020 Spotify AB
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { ApiTestRegistry } from '@backstage/core-api';
|
||||
import { MockErrorApi } from './apis';
|
||||
|
||||
export function createMockApiRegistry(): ApiTestRegistry {
|
||||
const registry = new ApiTestRegistry();
|
||||
|
||||
registry.register(MockErrorApi.factory);
|
||||
|
||||
return registry;
|
||||
}
|
||||
Reference in New Issue
Block a user