Test Levels and the Test Pyramid Questions
How unit, integration, component, end-to-end and contract tests fit together and where each provides the most value. Covers the test pyramid and the competing shapes proposed against it (the testing trophy and the honeycomb), multi-layer test architecture, contract testing as the seam between services, choosing the right level to catch a given class of defect cheaply, and what to run per commit versus per release. Includes the cost and confidence trade-offs between fast low-level tests and slower, broader system tests. The scope is which level a test belongs at and why. Deciding how much to invest in testing and where to prioritize under time pressure is covered separately.
You are testing a RESTful web application built from a React single-page application, a Node.js REST API, a PostgreSQL database, and an external payment gateway. For each test-pyramid tier (unit, integration, end-to-end), list four concrete example tests you would create, name a common tool or library for each example, and justify why each test belongs at that tier: what it verifies, and what it depends on.
Sample Answer
For a RESTful web application (React SPA, Node.js REST API, PostgreSQL, external payment gateway), each pyramid tier should own a different, non-overlapping slice of confidence, and the tests below make that concrete.
Unit tier (four examples)
- Discount/price calculator: a pure function
calculateDiscount(price, tier); verifies core business math, e.g. Jest for the frontend or a plain test runner on the backend. - React component render logic: does the checkout form component render a validation error when the card field is empty; React Testing Library.
- Request validator: does the order-creation handler reject a negative price before touching the database; a plain Jest unit test with mocked input, no HTTP or DB involved.
- Payment-gateway response parser: given a sample JSON response from the gateway, does your parser extract the correct transaction ID and status; a pure-function Jest unit test with a hard-coded fixture, no real network call.
Each of these verifies one piece of logic in isolation and depends on nothing external, which is why they can run in milliseconds.
Integration tier (four examples)
- API-to-database write path: POST an order to the real Node API running against a real (test) PostgreSQL instance, then query the database directly to confirm the row and its computed total are correct; Supertest plus a real Postgres test container.
- Repository layer against Postgres: an ORM query (e.g., a Prisma or TypeORM query) that joins orders and customers, run against a seeded test database via Testcontainers, to catch a wrong join or a migration mismatch a mocked-DB unit test would miss.
- Payment-gateway client against the gateway's sandbox: using an HTTP client library such as Axios (or the gateway's official Node.js SDK if one is provided), call the gateway's real sandbox endpoint (not your parser in isolation) to confirm your client sends a well-formed request and correctly handles the sandbox's real success and decline responses.
- React SPA against a mocked API layer: render the checkout page and confirm it calls the real API client code (not the component logic alone) and correctly updates state on a real HTTP response, using a tool like MSW (Mock Service Worker) to intercept only the network boundary, not the application code.
Each of these proves two real components agree on a contract (route shape, SQL schema, gateway request format) that a unit test, by construction, cannot check because it never invokes the second component for real.
End-to-end tier (four examples)
- Full checkout journey: drive the real React SPA in a real browser through add-to-cart, checkout form, and payment, against the real (or sandboxed) full stack, using Playwright or Cypress, to prove the whole assembled system delivers a working checkout.
- Payment failure path end-to-end: using Playwright or Cypress, submit a card the gateway's sandbox is configured to decline, and confirm the SPA shows the correct user-facing error, proving the failure path is wired correctly all the way through, not just handled by the parser in isolation.
- Session and auth flow: using Playwright or Cypress, log in, add an item, refresh the page, and confirm the cart persists, exercising the real session/cookie mechanism no lower-level test touches.
- Order confirmation and receipt: using Playwright or Cypress to complete the purchase, combined with a test email-capture tool such as Mailhog or Mailtrap, confirm a confirmation email or receipt page reflects the correct final total, proving the pricing logic, the database write, and the presentation layer all agree once wired together for real.
Why each test belongs where it does
The dividing line is what would have to be REAL for the test to fail the way it's meant to: the unit tests fail only if the pure logic is wrong; the integration tests fail only if two real components disagree, even when each one's internal logic is correct in isolation; the end-to-end tests fail only if something in the full assembly, including things no lower test can see (routing, session state, real gateway behavior), is broken.
Trade-offs and pitfalls
The most common mistake with this stack specifically is testing the payment-gateway integration primarily at the end-to-end level because "it's the riskiest part": that inflates the slowest, flakiest tier with coverage that a much cheaper integration test against the gateway's sandbox could provide almost as well. Reserve end-to-end for the few journeys where the VALUE is specifically in proving the pieces are wired together, and push everything else down a tier.
As a Test Automation Engineer, describe where each of the following should execute in a CI/CD pipeline for a typical web application: unit tests, component tests, integration tests, UI (Selenium-style) tests, and performance tests. For each type, explain the trade-off between speed and confidence it represents, and suggest a gating strategy: which types should be able to block a merge, and which should run later without blocking developers.
Sample Answer
Five test types map to three CI/CD stages, based on how much confidence each buys versus how much time it costs.
Where each type executes, and why
| Type | Where it runs | Speed vs confidence | Gating strategy |
|---|---|---|---|
| Unit | Every commit, pre-merge | Very fast, narrow confidence (proves logic, not wiring) | Blocks merge; failing a unit test almost always means the change is genuinely broken |
| Component | Every commit, pre-merge | Fast, slightly broader confidence (proves a component behaves correctly with its immediate collaborators) | Blocks merge, same rationale as unit tests |
| Integration | Pre-merge, on a curated subset; full suite nightly | Moderate speed, meaningfully higher confidence (proves real wiring to a database or service) | The curated PR subset blocks merge; the full nightly suite reports but does not block an already-merged commit, instead raising an alert for follow-up |
| UI (Selenium-style) | Nightly, or a small smoke subset pre-merge | Slow, highest realism for user-facing behavior, but also the highest flakiness risk | Only a small, high-value smoke subset blocks merge; the rest runs later and reports without blocking, since blocking on a flaky suite trains developers to ignore or bypass the gate |
| Performance | Nightly or on a fixed schedule, rarely per-commit | Slowest, and its "confidence" is about a different question (capacity and latency, not correctness) | Never blocks a merge directly; instead it feeds an alert when a regression crosses a defined threshold, since performance results are noisier commit-to-commit than correctness results |
To place the top two rows precisely: a component test differs from a unit test by including a piece's real in-process collaborators instead of mocking everything, and differs from an integration test by still faking anything external like a database or network call.
The underlying trade-off, made explicit
Unit and component tests buy fast, precise confidence about logic, which is why they are the safe types to let block every merge: a false positive is rare and a true positive is almost always worth stopping the merge for. Integration and UI tests buy broader, more realistic confidence, but at meaningfully higher cost and with real risk of flakiness producing false positives, so only a small, carefully curated slice of them should be allowed to block a merge; the rest should run on a slower cadence where a failure gets investigated without holding up unrelated work. Performance tests answer a different question entirely (capacity, not correctness) and are noisy enough commit-to-commit that gating a merge on them directly would produce too many false alarms; they belong in a monitored, threshold-based alerting flow instead.
Trade-offs and pitfalls
The main pitfall is over-blocking: putting the full UI or performance suite in the merge-blocking path "to be safe" reliably backfires, because the resulting slow, occasionally-flaky gate trains developers to rerun blindly or bypass it, which defeats the entire purpose of having a gate. The discipline is choosing a SMALL, high-confidence subset for the blocking path and trusting the rest of the suite, running on a faster feedback loop than "never," to catch what the blocking subset misses.
For a payment flow that integrates with a third-party gateway, evaluate the trade-offs of three approaches: (A) end-to-end tests running against the gateway's sandbox, (B) integration tests that mock the gateway's responses, and (C) contract tests verifying the request and response schemas between your service and the gateway. Explain where contract tests sit relative to integration and end-to-end tests and what problem they solve that the other two do not, then recommend which of the three you would run on every pull request versus nightly, and justify your choice by risk and cost.
Sample Answer
Contract tests exist to solve a problem neither end-to-end nor mocked-integration tests solve well: proving your service and the gateway agree on the SHAPE of their interaction, without needing the real gateway running and without silently drifting out of sync with what the gateway actually does.
Where contract tests sit, and what they uniquely solve
A contract test sits at the seam between integration and end-to-end: like an integration test, it runs fast and needs no live external dependency; like an end-to-end test, it is checking something about the REAL interface, not a hand-written assumption about it. Concretely, a contract test verifies that a captured or agreed-upon schema (which fields exist, their types, allowed values) for the gateway's request and response still holds, and critically, this contract can be verified independently on each side: your service checks it against the contract, and (in a full consumer-driven setup) the gateway's own team checks their real implementation against that same contract, so drift is caught the moment either side changes, at unit-test speed, without needing both systems running together in the same test.
Why (B), a hand-mocked integration test, is not equivalent
An integration test that mocks the gateway's responses is only as good as the assumptions baked into the mock: if the team writes the mock once and the gateway later changes its real response shape, the mocked test keeps passing forever, having silently drifted from reality. This is exactly the gap a contract test closes, since a contract test is verified against an actual agreed specification (or a captured real response), not an assumption the test author wrote down once and never revisited.
Evaluating the three approaches for a payment flow
- (A) End-to-end against the sandbox: highest realism (a real request genuinely reaches something resembling the gateway), but slowest and most fragile, since it depends on the sandbox's availability, network conditions, and test-account state, none of which your team controls.
- (B) Mocked integration tests: fast and reliable to run, but only as trustworthy as the mock's freshness, with the drift risk described above.
- (C) Contract tests: fast like (B), but without the drift risk, since the contract itself is the source of truth both sides verify against, rather than an assumption one side wrote down.
A worked, executable contract test
CONSUMER_CONTRACT = {
"required_fields": {"transaction_id": str, "status": str, "amount_cents": int},
"allowed_status_values": {"succeeded", "declined", "pending"},
}
def verify_contract(response_body, contract):
violations = []
for field, expected_type in contract["required_fields"].items():
if field not in response_body:
violations.append(f"missing required field: {field}")
elif not isinstance(response_body[field], expected_type):
violations.append(f"field '{field}' has wrong type")
if "status" in response_body and response_body["status"] not in contract["allowed_status_values"]:
violations.append(f"unexpected status value: {response_body['status']!r}")
return violations
Run against the CURRENT provider shape ({"transaction_id": "txn_abc123", "status": "succeeded", "amount_cents": 4999}), this correctly returns zero violations. To prove the check is real and not a no-op, it was also run against two realistic breaking changes: a provider release that renames amount_cents to amount (returned violation: missing required field: amount_cents), and a provider that introduces a new status value the contract never declared, such as "requires_action" (returned violation: unexpected status value: 'requires_action'). Both breaking changes were caught, at zero network cost and in well under a millisecond, exactly the class of drift a stale hand-written mock would miss silently.
Recommendation: what runs on every pull request versus nightly
Run the contract test (C) on every pull request: it's fast, deterministic, and catches the highest-value class of bug (a broken assumption about the gateway's real shape) at the lowest cost. Run a smaller number of mocked integration tests (B) on every pull request too, for the request/response HANDLING logic the contract test doesn't cover (how your code reacts to a decline, a timeout, a malformed amount). Reserve the sandbox end-to-end test (A) for nightly, since it is the slowest and least reliable of the three, and its unique value, proving the real network path and real gateway behavior work together, does not need to be re-proven on every single commit.
Trade-offs and pitfalls
A contract test is only as good as how the contract itself stays current: without a process (ideally automated, via a shared contract broker - a service, such as a Pact Broker, where consumer teams publish the contracts they depend on and provider teams look up every contract they need to satisfy) for the gateway team to verify their real implementation against the same contract your consumer test uses, a "contract" test degrades back into the same drift risk as a hand-mocked test, just with extra ceremony. The value of contract testing comes specifically from BOTH sides verifying against a shared source of truth, not from the format of the test itself.
You are adding a small new feature to an existing web app: a per-user settings toggle that changes UI behavior. Which tests would you write first, and why? Specify the concrete unit, integration, and end-to-end tests you would create, which tests could reasonably be postponed or executed manually instead, and how you would weigh risk, regression likelihood, and return on investment in that decision.
Sample Answer
For a small, contained change like a per-user settings toggle, the order you write tests in should mirror how cheaply each level can rule out a class of bug, not an arbitrary checklist.
Which tests to write first, and why
- Unit test first: does the function that decides the toggle's effective value (given the stored setting, any default, and any override) return the right value for on, off, and unset states. This is the cheapest possible check on the actual logic and should exist before anything else, since if the logic itself is wrong, no amount of higher-level testing will reliably catch every case.
- Integration test second: does saving the toggle's new value actually persist it correctly (a real database write and read-back), and does the API endpoint that exposes the setting return the correct value after a save. This proves the logic from step 1 is correctly wired to real storage, which the unit test cannot show.
- One end-to-end test: a single test that toggles the setting through the real UI and confirms the resulting UI behavior actually changes, proving the whole path (UI action, API call, storage, and the resulting render) is wired together correctly for a real user. One is enough here: additional UI-level variations (different starting states, different pages) are better covered at the unit or integration level instead.
What to postpone or handle manually
Visual polish around the toggle (exact spacing, animation) is better handled by manual or exploratory testing rather than an automated test, since automating a purely visual detail for a low-risk, easily-reverted feature rarely pays back its maintenance cost. Similarly, exhaustive combinations of the toggle with every other unrelated setting are not worth automating up front for a small, isolated feature; a manual spot-check covers that risk more cheaply until real usage shows a combination actually matters.
Weighing risk, regression likelihood, and ROI
The toggle's blast radius (does it interact with billing, security, or just cosmetic UI behavior) should set how much automated coverage it earns: a purely cosmetic toggle justifies exactly the three tests above and nothing more, while a toggle that gates paid functionality would justify more integration-level coverage of its interaction with the billing system specifically. Regression likelihood also matters: an isolated, rarely-touched feature is unlikely to be broken by unrelated future changes, so its test investment can stay minimal; a setting that many other features read is worth more integration coverage precisely because future unrelated changes are more likely to break it.
A harder version of the same judgment: a runtime, per-tenant feature flag
The same reasoning scales up for a runtime feature flag that can be toggled per tenant and rolled out to a percentage of users, but the stakes and the required levels both grow. Here you need coverage at four levels rather than three: unit tests for the flag-evaluation logic itself (given a tenant and a rollout percentage, does it correctly decide on or off); integration tests confirming flag state changes are correctly read and cached; a canary-level check confirming a partial rollout percentage is honored in practice (roughly the right proportion of requests see the new behavior, no more); and end-to-end tests confirming no leakage occurs between tenants (a flag enabled for tenant A never leaks its effect to tenant B) and that a rollback of the flag takes effect promptly. The extra canary level and the explicit tenant-isolation and rollback checks exist because the blast radius of getting a runtime, partial rollout wrong (accidentally exposing new behavior to the wrong users, or being unable to roll it back quickly) is categorically larger than a simple settings toggle's.
Trade-offs and pitfalls
The pitfall for the small-toggle case is over-testing a low-risk feature out of habit, writing UI-level tests for every state combination when a single end-to-end test plus solid unit coverage would give equivalent confidence at a fraction of the cost. The pitfall for the feature-flag case is the opposite: under-testing because "it's just a flag," when in practice a flag with per-tenant, partial-rollout semantics is closer in risk to a small distributed system than to a simple toggle, and deserves the fuller four-level treatment above.
Tell me about a time you discovered a production bug that was caused by missing or insufficient tests. Using the STAR structure, describe the situation, the task you were responsible for, the actions you took to fix the bug and improve the tests or process (including which test level was missing and why), and the measurable result afterward.
Sample Answer
A strong answer to this question names the specific test level that was missing, not just "we didn't have enough tests," because the level tells the interviewer exactly what you learned and whether your fix addressed the real gap.
How to structure the STAR response
Situation: describe the system and the context concisely, for example a checkout service where a promotional-discount feature shipped and, in production, allowed two discount codes to be combined when the business rule required only one to apply at a time.
Task: state your specific responsibility, for example being the engineer or QA owner responsible for the checkout service's test coverage and for triaging the incident once it was reported.
Action: this is the part worth being most concrete about. Two honest, common shapes:
- The bug existed at the UNIT level (the discount-combination rule itself was wrong) but no unit test covered that specific combination of inputs, only the single-discount case; the integration and end-to-end tests that existed happened to use test data that never exercised two codes together, so they passed without ever exercising the buggy path. The fix: add the missing unit test covering the combination case, verify it fails against the buggy code and passes against the fix, and then audit for other similarly-unexercised input combinations in the same rule.
- The bug existed at the INTEGRATION level (each discount's logic was individually correct, but the two didn't compose correctly once wired through the real order-total calculation, a case unit tests of each discount rule in isolation could not see). The fix: add an integration test that exercises the real combined path, not just each rule mocked in isolation.
Either shape is a legitimate, honest answer; the point is naming precisely which level was missing and why the existing suite's blind spot let the bug through, then closing that specific gap rather than adding coverage generically.
Result: describe the outcome concretely but honestly: for example, that specific discount-combination bug did not recur, and the broader audit of the same rule surfaced and closed a small number of similarly-unexercised input combinations before they caused an incident, giving you a real, verifiable before/after data point (the audit finding count) rather than an invented precision metric.
Trade-offs and pitfalls
The common way this answer goes wrong in an interview is staying vague ("we added more tests and it got better"), which gives the interviewer no way to judge your actual technical judgment; naming the specific test level, the specific gap in that level's coverage, and the specific fix is what turns a generic incident story into evidence of real testing judgment. A second pitfall is inventing a precise-sounding improvement metric you didn't actually measure; if you don't have a real number, describe the outcome qualitatively (no recurrence, caught in the audit before shipping) rather than fabricating one.
Unlock Full Question Bank
Get access to all 21 Test Levels and the Test Pyramid interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.