Skip to content

Interview PrepTesting · Core

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.

end-to-endintegrationunitfew, slowsome, real databasemany, fastmost confidence eachfastest feedback
A wide base of fast checks, a narrow top of slow ones. Many unit tests give quick, precise feedback. Fewer integration tests check that real pieces fit. A small number of end-to-end tests prove the key journeys.
UnitIntegrationEnd-to-end
ScopeOne function or classA route plus database, or two servicesThe whole system
DependenciesReplaced with fakesReal ones, often in containersReal
SpeedMillisecondsSecondsSeconds to minutes
CatchesLogic mistakesWiring, SQL, config, serialisationBroken journeys, deployment problems
Failure points toThe exact functionA small areaSomewhere 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 choiceWhy it helps
buildApp(deps) separate from listenThe app can be started in a test without a real port or production services (the structure question)
Services that do not touch req and resBusiness rules can be checked directly
Dependencies passed in, not imported globallyA fake payment provider can be substituted
Configuration validated in one moduleTests can supply their own configuration
Time and randomness behind small helpersResults 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.

RunnerNotes
JestMature, very common, rich mocking; ES modules and TypeScript need extra setup
VitestJest-like interface, fast, native ESM and TypeScript, pairs with Vite
node --testBuilt 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:

CheckExample
Status codesPOST /orders without a token returns 401
ValidationA negative quantity returns 400 with a field error
Response shapeThe body matches the documented schema
HeadersLocation is set on 201, security headers are present
Error formatUnknown 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.

DoublePurposeAnswers the question
StubProvide canned responses"What if the payment provider says declined?"
SpyRecord calls"Was the receipt email sent, and to whom?"
MockPre-programmed expectations"Was charge called exactly once with £24.99?"
FakeA working, simple implementationAn 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 itDo not mock it
Payment, SMS and email providersYour own services and pure functions
Other teams' services in unit testsYour database in integration tests: run a real one
The current time, timers, random IDsThe function or class being tested
Failures: timeouts, 503, dropped connectionsLibraries' 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.

ApproachRealismSpeedIsolation
Mocked repositoryLow: no SQL runsFastestPerfect
In-memory or different databaseMedium: differs from productionFastGood
Shared test database serverHighMediumPoor: tests collide
TestcontainersHigh: same engine and versionMedium, a few seconds to startGood: 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.

checkoutconsumerrecords what it needscontractGET /orders/42 →id, status, totalPenceorders serviceproviderverified each build① publish② verify③ field removed: build fails
A written promise between two services. ① The consumer publishes what it relies on. ② The provider checks every build against it. ③ A change that would break the consumer fails the provider's build, long before production.
ApproachCatches broken API changesSpeedNeeds both services running
End-to-end testsYesSlowYes, plus all their dependencies
Contract testsYesFastNo
OpenAPI checks onlyPartly: the spec, not real behaviourFastNo

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:

AreaCases
AuthenticationMissing token · malformed token · wrong signature · expired · wrong audience or issuer · valid
Authorisation by roleEach role on each sensitive route; the lowest role on admin routes
OwnershipUser A reading, changing or deleting user B's order: must fail
Error handlingValidation error · not found · conflict · unexpected exception · error after headers sent
LeaksNo 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:

ScenarioExpected behaviour
Two 503s, then successThree attempts, success returned
400 on the first callNo retry; error returned immediately
No answer at allGives up after the timeout, with a timeout error
429 with Retry-After: 2Waits about two seconds before retrying
Every attempt failsStops after the maximum, total time within the budget
Retried POSTSame 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).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Express & REST APIs
Express
REST API design
Testing
Other topics
Nothing picked yet