PlatformEngr® Backstage plugins course

Cheat notes · Module 03 · The backend plugin

Test the backend plugin

A five-minute review for when you have done this module and want it back in your head. Open the full module for the steps and the lab, or the full text to print.

The idea

A plugin is wiring, so test it the way callers use it: start the real plugin with startTestBackend, fake only what you must, and send HTTP requests with supertest.

Remember

  • startTestBackend({ features }): starts a backend with only the features you list. Core services you do not give are mocks: an in-memory database, a logger, auth that lets requests through.
  • mockServices: replace one service with your behaviour, e.g. mockServices.permissions.factory({ result: AuthorizeResult.DENY }).
  • catalogServiceMock.factory({ entities }): a catalog with only the entities you give it (from @backstage/plugin-catalog-node/testUtils).
  • supertest: request(server).post('/api/readiness/evaluate').send({...}).expect(404).
  • Isolation: each test starts its own backend, so tests never share data.

Pitfalls

  • Removing the scheduler's initialDelay: the job runs during startup, and the test that expects no scorecard yet gets 200 instead of 404. Startup is busy; background work can wait.
  • Editing a failing test to pass before asking whether the behaviour was meant to change.

Commands

cd plugins/readiness-backend && yarn test --watchAll=falseRun the plugin's tests once

A test over HTTP

const { server } = await startTestBackend({
  features: [
    readinessPlugin,
    catalogServiceMock.factory({ entities: [checkout] }),
  ],
});
const res = await request(server)
  .post('/api/readiness/evaluate')
  .send({ entityRef: 'component:default/checkout' });
expect(res.status).toBe(200);

Test yourself

Answer in your head first, then open the answer.

What does startTestBackend give you that a unit test on scoreEntity does not?

The real plugin wiring: services, routes, database and schedule.

How do you test the plugin with an empty catalog?

Add catalogServiceMock.factory({ entities: [] }) to the features.

A test fails after a change. What do you check first?

Whether the behaviour the test describes was meant to change.

Where module 03 leaves you: Two passing tests in readiness-backend that start the plugin with an in-memory database and a fake catalog. Merged.