Appearance
Testing Concepts
69. What is the difference between unit, integration, and end-to-end testing?
The short answer
A unit test checks one small piece, such as a pricing function, on its own, with its dependencies replaced, so it is very fast and pinpoints failures exactly. An integration test checks several real pieces working together, such as an API route with a real database, which catches wiring, query and configuration mistakes. An end-to-end test drives the whole system the way a user would, through the real front end or public API, which proves the main journeys work, but is slow and more fragile. A healthy suite has many unit tests, fewer integration tests and a handful of end-to-end tests.
| Unit | Integration | End-to-end | |
|---|---|---|---|
| Scope | One function or class | A route plus database, or two services | The whole system |
| Dependencies | Replaced with fakes | Real ones, often in containers | Real |
| Speed | Milliseconds | Seconds | Seconds to minutes |
| Catches | Logic mistakes | Wiring, SQL, config, serialisation | Broken journeys, deployment problems |
| Failure points to | The exact function | A small area | Somewhere in the system |
An example of each for an order service: a unit test checks the discount calculation for a basket; an integration test sends POST /orders to the app and checks a row appears in a real Postgres; an end-to-end test signs in through the website, adds an item, pays with a test card and sees the confirmation page.
70. How do you test a Node.js application?
The short answer
Structure the code so it can be tested: keep business rules in plain functions and services that do not depend on Express, and build the app with a function that receives its dependencies. Then cover the business logic with fast unit tests, cover HTTP routes and database queries with integration tests against a real database in a container, and cover a few critical journeys end to end. Run everything automatically in CI on every pull request, and measure what matters, such as whether risky paths are covered, rather than chasing a coverage number.
What makes a Node.js service easy to test:
| Design choice | Why it helps |
|---|---|
buildApp(deps) separate from listen | The app can be started in a test without a real port or production services (the structure question) |
Services that do not touch req and res | Business rules can be checked directly |
| Dependencies passed in, not imported globally | A fake payment provider can be substituted |
| Configuration validated in one module | Tests can supply their own configuration |
| Time and randomness behind small helpers | Results are repeatable |
A typical setup: a test runner such as Vitest, Jest or Node.js's built-in runner, Supertest for calling routes in process, Testcontainers for real databases, and a CI job that runs the suite on every change. What runs where in a pipeline is covered in the pipeline design questions.
71. What is Jest, and how is it used for backend testing?
The short answer
Jest is a widely used JavaScript test runner from Meta. It finds test files, runs them in parallel in isolated environments, provides assertion helpers, built-in mocking of functions and modules, timers you can control, snapshot comparison and coverage reports. For backends it is used to run unit and integration tests of Node.js services. Many newer TypeScript and Vite projects use Vitest, which has a nearly identical interface but native ES module and TypeScript support, and Node.js itself now ships a built-in test runner.
| Runner | Notes |
|---|---|
| Jest | Mature, very common, rich mocking; ES modules and TypeScript need extra setup |
| Vitest | Jest-like interface, fast, native ESM and TypeScript, pairs with Vite |
node --test | Built into Node.js, no dependency, simpler feature set |
What a runner gives you, whichever you choose: discovery of test files, isolation between files, parallel execution, a watch mode while you code, mocking utilities, fake timers and coverage reports that CI can publish.
72. What is Supertest, and how can it test Express endpoints?
The short answer
Supertest is a library for testing HTTP servers. You give it your Express app, and it starts the app on a temporary port inside the test process, sends real HTTP requests to it with a simple chained interface, and lets you check the status code, headers and body of the response. Because requests go through the whole middleware chain, routing, validation, authentication and error handling, it tests routes as clients really use them, without deploying anything.
What it is good at checking:
| Check | Example |
|---|---|
| Status codes | POST /orders without a token returns 401 |
| Validation | A negative quantity returns 400 with a field error |
| Response shape | The body matches the documented schema |
| Headers | Location is set on 201, security headers are present |
| Error format | Unknown routes return the standard problem format (the error responses question) |
Why it pairs with buildApp: the test builds the app with a test database and a fake payment provider, then Supertest exercises it. No port conflicts, no shared servers, and each test can run with its own data.
73. How do mocks, stubs, and spies differ?
The short answer
They are kinds of test doubles, stand-ins for real dependencies. A stub returns fixed answers so the code under test can run, such as a payment client that always says "approved". A spy wraps a real or fake function and records how it was called, so you can check afterwards that, for example, the email sender was called once with the right address. A mock is a fake with expectations built in: it is set up in advance with the calls it should receive, and the test fails if they do not happen. In everyday speech, people often call all of them mocks.
| Double | Purpose | Answers the question |
|---|---|---|
| Stub | Provide canned responses | "What if the payment provider says declined?" |
| Spy | Record calls | "Was the receipt email sent, and to whom?" |
| Mock | Pre-programmed expectations | "Was charge called exactly once with £24.99?" |
| Fake | A working, simple implementation | An in-memory repository instead of a database |
The trade-off: doubles make tests fast and let you produce rare situations, such as a timeout, on demand. Overused, they make tests check how code calls its collaborators rather than what it achieves, so tests break on every refactor while real bugs slip through (question 74).
74. What should you mock, and what should you avoid mocking?
The short answer
Mock what is slow, costly, non-deterministic or outside your control: third-party APIs such as payment providers and email services, the clock, random values, and network failures you need to simulate. Avoid mocking what you own and can run cheaply: your own business logic, your database, which you can run in a container, and the code under test itself. Mock at the boundary of your system, not in the middle of it, and prefer checking outcomes, such as the order row and the response, over checking internal calls.
| Mock it | Do not mock it |
|---|---|
| Payment, SMS and email providers | Your own services and pure functions |
| Other teams' services in unit tests | Your database in integration tests: run a real one |
| The current time, timers, random IDs | The function or class being tested |
Failures: timeouts, 503, dropped connections | Libraries' internals, such as how an ORM builds SQL |
Why mocking the database is risky: a mocked repository happily "returns" data for a query that would fail in Postgres, or ignores a unique constraint. The test passes, production fails. A real database in a container catches those mistakes (question 75).
A useful rule: if a test has to change whenever you refactor code without changing behaviour, it is probably mocking too much.
75. What are test containers, and when should they be used?
The short answer
Testcontainers is a library that starts real dependencies, such as Postgres, Redis, Kafka or a mail server, in throwaway Docker containers during a test run, gives the tests their connection details, and removes the containers afterwards. Integration tests then run against the same database engine and version as production, instead of an in-memory imitation, while staying isolated and repeatable on any machine with Docker. Use them for tests of queries, migrations, transactions and anything that depends on real database behaviour.
| Approach | Realism | Speed | Isolation |
|---|---|---|---|
| Mocked repository | Low: no SQL runs | Fastest | Perfect |
| In-memory or different database | Medium: differs from production | Fast | Good |
| Shared test database server | High | Medium | Poor: tests collide |
| Testcontainers | High: same engine and version | Medium, a few seconds to start | Good: fresh per run |
Making them fast enough: start one container for the whole test run rather than per test, run migrations once, and reset data between tests with transactions that are rolled back or by truncating tables. In CI, the runner needs Docker available.
76. What is contract testing, and why is it useful for microservices?
The short answer
Contract testing checks that two services agree on the API between them, without running both together. In consumer-driven contract testing, with tools such as Pact, each consumer records the requests it makes and the responses it relies on; those recordings become a contract, and the provider's build checks that it still satisfies every consumer's contract. It catches breaking API changes, such as a renamed field, before deployment, which is far cheaper and faster than end-to-end tests across many services.
| Approach | Catches broken API changes | Speed | Needs both services running |
|---|---|---|---|
| End-to-end tests | Yes | Slow | Yes, plus all their dependencies |
| Contract tests | Yes | Fast | No |
| OpenAPI checks only | Partly: the spec, not real behaviour | Fast | No |
When it is worth it: many services owned by different teams, changing independently. For two services owned by one team, checking both against a shared OpenAPI document is often enough (the OpenAPI question).
77. How do you test authentication, authorization, and error-handling middleware?
The short answer
Test them through the routes they protect, as a client would. For authentication, send requests with no credential, an expired one, a forged or wrongly signed one, and a valid one, and check you get 401 or success. For authorisation, try each role and, crucially, one user trying to read or change another user's record, expecting 403 or 404. For the error handler, trigger each kind of error and check the status, the standard error format, that no stack trace or internal message leaks, and that the error was logged.
The cases worth covering, as a checklist:
| Area | Cases |
|---|---|
| Authentication | Missing token · malformed token · wrong signature · expired · wrong audience or issuer · valid |
| Authorisation by role | Each role on each sensitive route; the lowest role on admin routes |
| Ownership | User A reading, changing or deleting user B's order: must fail |
| Error handling | Validation error · not found · conflict · unexpected exception · error after headers sent |
| Leaks | No stack traces, SQL or internal hostnames in any error body (the leaks question) |
The ownership case is the one teams forget, and it is the most common real security bug in APIs: changing an ID in the URL and getting someone else's data (the authorisation middleware question). Every endpoint that takes an ID deserves that check.
Signing test tokens: use a key pair created for the tests and configure the app to trust it, rather than disabling verification in test mode, which is how verification gets accidentally disabled in production too.
78. How do you test retry logic, timeouts, and failure scenarios?
The short answer
Make failures happen on purpose and check the behaviour. Replace the dependency with a fake, or a programmable local server, that fails the first two calls and succeeds on the third, that never answers, or that answers slowly, and check the code retries the right number of times, stops on non-retryable errors, gives up within its timeout, and returns a clean error. Use controllable fake timers so backoff delays do not make the suite slow, and check that retried operations are not applied twice.
Scenarios worth covering:
| Scenario | Expected behaviour |
|---|---|
Two 503s, then success | Three attempts, success returned |
400 on the first call | No retry; error returned immediately |
| No answer at all | Gives up after the timeout, with a timeout error |
429 with Retry-After: 2 | Waits about two seconds before retrying |
| Every attempt fails | Stops after the maximum, total time within the budget |
Retried POST | Same idempotency key every time; one charge, not two (the retries question) |
Testing at the system level: in staging, chaos experiments, such as adding latency or killing a dependency, check that timeouts, retries and circuit breakers work together under real load (the chaos engineering question).