backend-test-utils: only clean up test backends after all tests

Co-authored-by: Fredrik Adelöw <freben@gmail.com>
Co-authored-by: Johan Haals <johan.haals@gmail.com>
Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2022-12-14 11:27:43 +01:00
parent deaa069b76
commit 73a8f69d62
3 changed files with 38 additions and 13 deletions
@@ -23,6 +23,38 @@ import {
} from '@backstage/backend-plugin-api';
import { startTestBackend } from './TestBackend';
// This bit makes sure that test backends are cleaned up properly
let globalTestBackendHasBeenStopped = false;
beforeAll(async () => {
await startTestBackend({
services: [],
features: [
createBackendModule({
moduleId: 'test.module',
pluginId: 'test',
register(env) {
env.registerInit({
deps: { lifecycle: coreServices.lifecycle },
async init({ lifecycle }) {
lifecycle.addShutdownHook({
fn() {
globalTestBackendHasBeenStopped = true;
},
});
},
});
},
})(),
],
});
});
afterAll(() => {
if (!globalTestBackendHasBeenStopped) {
throw new Error('Expected backend to have been stopped');
}
});
describe('TestBackend', () => {
it('should get a type error if service implementation does not match', async () => {
type Obj = { a: string; b: string };
@@ -117,7 +149,6 @@ describe('TestBackend', () => {
const backend = await startTestBackend({
services: [],
features: [testModule()],
autoStop: 'never',
});
expect(shutdownSpy).not.toHaveBeenCalled();
@@ -51,7 +51,6 @@ export interface TestBackendOptions<
},
];
features?: BackendFeature[];
autoStop?: 'afterEach' | 'never';
}
const defaultServiceFactories = [
@@ -60,7 +59,7 @@ const defaultServiceFactories = [
lifecycleFactory(),
];
const backendInstances = new Array<Backend>();
const backendInstancesToCleanUp = new Array<Backend>();
/** @alpha */
export async function startTestBackend<
@@ -71,7 +70,6 @@ export async function startTestBackend<
services = [],
extensionPoints = [],
features = [],
autoStop = 'afterEach',
...otherOptions
} = options;
@@ -107,9 +105,7 @@ export async function startTestBackend<
services: factories,
});
if (autoStop) {
backendInstances.push(backend);
}
backendInstancesToCleanUp.push(backend);
backend.add({
id: `---test-extension-point-registrar`,
@@ -141,15 +137,15 @@ function registerTestHooks() {
}
registered = true;
afterEach(async () => {
for (const backend of backendInstances) {
afterAll(async () => {
for (const backend of backendInstancesToCleanUp) {
try {
await backend.stop();
} catch (error) {
console.error(`Failed to stop backend after test, ${error}`);
console.error(`Failed to stop backend after tests, ${error}`);
}
}
backendInstances.length = 0;
backendInstancesToCleanUp.length = 0;
});
}