Learning on Web Dev Open is free for all.

Backend Engineering > Proving it works, then shipping itWhat is worth testing in an API
Phase 05Proving it works, then shipping it274 of 434

What is worth testing in an API

Test the contract at the boundary, not the internals. A test that survives a refactor is worth ten that do not.

Concept14 minAI pair

The tests that pay for themselves in a service are the ones that send a request and assert on the response: status, shape, and the important fields. They exercise routing, middleware, validation, the handler and serialisation together, they are written in the language of the contract, and they survive you rewriting the inside. Unit tests are for the pieces with real logic: a pricing rule, a date calculation, a permission matrix.

The database question has three answers and no perfect one. A real database in a container is the most faithful and the slowest to set up. An in-memory or ephemeral instance per test run is a good middle. Mocking the data layer is fastest and tests the least, since most bugs at this level are about queries, and a mocked query cannot be wrong. Start with a real database and a truncate between tests; revisit when it hurts.

One habit is worth more than any coverage number: when you fix a bug, write the test that would have caught it first, and watch it fail. That builds a suite shaped like your actual mistakes rather than like your optimism, and it is the only reliable way to stop reintroducing the same thing.

You should now be able to

  • Choose a testing level for a given behaviour
  • Write a test against HTTP rather than against a function
  • Decide what to do about the database in tests
Ask the community

Loading…