Test Case Design and Edge Case Analysis Questions
Systematically deriving the cases, inputs, and conditions most likely to expose defects. Covers formal test-design techniques (equivalence partitioning, boundary value analysis, decision tables, state transitions, and pairwise/combinatorial design) and writing clear, maintainable test cases with documented expected results. Also covers the edge-case mindset: boundary conditions, invalid and unexpected inputs, corner cases, and the attention to detail that anticipates failures when validating complex behavior.
Given the following JavaScript function, identify and fix edge cases (empty array, non-number values, extremely large numbers) and return a robust implementation in ES6 that behaves predictably:
function average(nums) { return nums.reduce((a,b)=>a+b,0)/nums.length; }
Explain your design decisions regarding empty input handling, validation, and numeric stability.
Sample Answer
Direct answer
The given average function has three latent bugs: it returns NaN (Not a Number) on an empty array instead of failing loudly, it silently propagates NaN on any non-number element instead of rejecting it, and it accumulates floating-point rounding error on inputs with very different magnitudes because a plain reduce-based sum has no error compensation. A robust version validates its input explicitly and uses Kahan summation to control the numeric-stability failure mode.
Structured elaboration
- Empty array:
[].reduce((a,b)=>a+b,0) / [].lengthis0 / 0, which isNaNin JavaScript, not an exception. A caller checkingif (result)will treatNaNas falsy and may silently branch into unexpected logic three calculations downstream, far from where the actual problem (an empty array) occurred. The fix throws immediately, at the fault, with a message naming exactly what went wrong. - Non-number values:
reducewill happily coerce or fail unpredictably depending on the value (a string that looks numeric gets implicitly converted in+, giving a wrong-but-plausible result rather than an error); the fix validates every element istypeof === 'number' && !Number.isNaN(value)before accumulating, and names the specific offending index in the error. - Numeric stability for extremely large numbers has two DISTINCT failure modes, and it matters which one a given input triggers:
- Sum overflow to
Infinity: if the running sum itself exceedsNumber.MAX_VALUE(roughly 1.8 x 10^308), it overflows toInfinity, even when the true AVERAGE would be perfectly representable. Neither a naivereducenor Kahan summation avoids this, because both accumulate a running sum; avoiding it entirely requires a different algorithm (an incremental/streaming mean update, not a sum-then-divide). - Precision loss from mixing very different magnitudes: adding a small value to a much larger running total can lose the small value's contribution entirely to floating-point rounding. Kahan summation tracks a compensation term that recovers most of this lost precision, and genuinely helps here, unlike the overflow case above.
- Sum overflow to
Worked example (executed, ES6/ECMAScript 2015)
function average(nums) {
if (!Array.isArray(nums)) throw new TypeError('average() expects an array');
if (nums.length === 0) throw new RangeError('average() of an empty array is undefined');
let sum = 0, compensation = 0;
for (let i = 0; i < nums.length; i++) {
const value = nums[i];
if (typeof value !== 'number' || Number.isNaN(value)) {
throw new TypeError(`average(): element at index ${i} is not a finite number: ${JSON.stringify(value)}`);
}
const y = value - compensation, t = sum + y;
compensation = (t - sum) - y;
sum = t;
}
return sum / nums.length;
}
Run against the original buggy function and this fixed version side by side:
original_empty_array: returned NaN | fixed_empty_array: threw RangeError("average() of an empty array is undefined")
original_non_number: returned NaN | fixed_non_number: threw TypeError("average(): element at index 1 is not a finite number: \"x\"")
original_NaN_element: returned NaN | fixed_NaN_element: threw TypeError("average(): element at index 1 is not a finite number: null")
fixed_normal_case: returned 4 (average of [2,4,6])
original_sum_overflow: returned Infinity | fixed_sum_overflow_kahan_no_help: returned Infinity (two Number.MAX_VALUE inputs; Kahan does not help here, confirmed above)
original_large_magnitude_mix: returned 0 | fixed_large_magnitude_mix_kahan: returned 0 ([1e16, 1, -1e16]; both give the SAME result here, an honest finding, not a Kahan win on this specific input)
original_repeated_0.1_x1000: returned 0.09999999999999859 | fixed_repeated_0.1_x1000_kahan: returned 0.1 (1000 copies of 0.1; this is where Kahan's compensation measurably wins)
Trade-offs and pitfalls
The honest finding in the executed output above matters: Kahan summation does NOT help every large-number case, [1e16, 1, -1e16] returns 0 under both the naive and the Kahan version, because the value 1 is smaller than the rounding error already introduced by 1e16 + 1 before Kahan's compensation term ever gets a chance to track it; a candidate who claims Kahan "fixes" all large-number issues without checking is overclaiming. The repeated-0.1 case is where the real, measured benefit is (0.09999999999999859 vs. exactly 0.1), and that is the honest example to cite. A second pitfall is treating "throw on bad input" as strictly better without considering the caller's context; a data-pipeline aggregation that must never crash mid-batch might instead want to skip and log a bad element rather than throw, which is a legitimate design trade-off this fix intentionally does not make, and a candidate should say so explicitly rather than presenting throwing as the only correct choice.
Define the term 'edge case' (and 'corner case') in the context of software testing. Why does systematically identifying them matter more than testing only the happy path? Give at least eight concrete categories, spanning at least three different domains (a generic input-validation example, a production/reliability example, and a data or ML-pipeline example).
Sample Answer
Direct answer
An edge case (or corner case, when two or more boundary conditions intersect) is an input, state, or condition at the extreme or unusual end of what a system is expected to handle, distinct from the 'happy path' of typical, well-formed usage; systematically identifying them matters because production traffic and adversarial users reliably generate exactly these unusual conditions, while happy-path testing alone only proves the system works when everything goes as expected, which is rarely where real defects live.
Structured elaboration: eight categories, spanning multiple domains
- Empty/null: an empty list, a null field, a zero-length string. Example (general software): a search function called with an empty query string.
- Boundary/max-min: values exactly at, or one step past, a defined limit. Example (backend): a pagination
page_sizeparameter at exactly the server-enforced maximum. - Zero/negative: values a numeric field technically accepts as a type but that may be nonsensical for the domain. Example (SRE/production): a negative value in a counter that should only ever increase, signaling either overflow or a bug in the decrement logic.
- Duplicate: repeated values where uniqueness might be silently assumed. Example (general software): two items with the same ID in a list a system expects to be de-duplicated upstream.
- Malformed/invalid type: input that is the wrong shape or type entirely. Example (backend): a JSON field expected to be an integer arriving as a string or an array.
- Out-of-order/concurrent: events or requests arriving in an unexpected sequence, or overlapping in time. Example (SRE/production): a delivery-confirmation event for a message arriving before the message-sent event, due to network reordering.
- Very large/very small scale: inputs at a magnitude far outside typical testing. Example (data/ML pipeline): a categorical feature with hundreds of millions of unique values (e.g. a raw user ID) fed into a one-hot encoder, which can silently exhaust memory.
- Environment/locale-specific: behavior that only manifests under a specific timezone, locale, or platform. Example (general software): a date-parsing function that behaves correctly in the US locale but misinterprets day/month order elsewhere.
Worked example: why happy-path testing alone misses these
A login form tested only with a valid, well-formed email and a correct password will pass every happy-path test while shipping with a null-pointer crash on an empty password field, an infinite spinner on a 10,000-character email, or a silent security bypass on a SQL-injection-shaped username, none of which a happy-path suite would ever exercise, because by construction happy-path tests only feed the system inputs the developer already expected to work.
Trade-offs & pitfalls
Treating 'edge case' as synonymous with 'rare' is a common misconception: an empty list or a zero value is often one of the MOST common real-world inputs (a brand-new user's empty cart, a freshly-created account with no activity yet), not a rare corner case, which is exactly why the empty/null category above is listed first, not last; conflating 'edge case' with 'unlikely' leads teams to systematically under-test the cases that actually occur most often in a real user base's earliest interactions with a feature.
You need to ensure the checkout flow is robust across edge cases (payment provider failures, slow networks, multi-tab use, partial failures). Propose a balanced test suite across unit, integration, and E2E tests, listing specific test cases for edge behaviors, test data strategies, decisions for mocking versus using sandbox endpoints, and techniques to reduce E2E flakiness.
Sample Answer
Direct answer
A robust test suite for a checkout flow needs three layers with genuinely different jobs, not the same edge cases repeated at three levels: unit tests pin the exact logic of individual failure-handling decisions, integration tests verify the interaction between the client and the payment provider's contract (including sandbox behavior), and end-to-end (E2E) tests verify the small number of full user journeys that actually matter (a payment failure mid-flow, a multi-tab conflict, an interrupted network). Getting the split right, and being deliberate about mocking versus real sandbox endpoints, is what keeps this suite fast and trustworthy instead of slow and flaky.
Structured elaboration
| Layer | What it owns | Specific edge-case tests |
|---|---|---|
| Unit | Pure logic: given a specific provider response or error code, what does the checkout state machine decide to do next | Payment provider returns a declined-card error code vs. a network-timeout error code (these must route to different UI states, not one generic "payment failed" message); a duplicate submit is prevented by disabling the submit control the instant a request starts, tested by simulating two rapid submit events and asserting only one request fires |
| Integration | The real contract between the client code and the payment provider's actual API (application programming interface) shape, run against the provider's sandbox environment, not a hand-written mock of it | A sandbox-triggered decline response is parsed into the correct internal error type; a sandbox-triggered slow response (most providers' sandboxes support an artificial-delay test card or flag) is handled by the timeout logic without the UI hanging indefinitely; the client's idempotency-key header is actually present and correctly formed on a real request, which a hand-written mock cannot verify since it never sees the real serialized request |
| End-to-end | The handful of full user journeys where the FAILURE is the point, exercised through the real UI | Multi-tab: the same cart open in two tabs, one tab completes checkout, and the second tab's stale checkout attempt is rejected (or gracefully informed the order already completed) rather than double-charging; slow network: checkout submitted on a throttled connection shows an appropriate pending state rather than appearing to hang or allowing a second submit; partial failure: payment succeeds but the confirmation page fails to load, and reloading or returning to the site does not re-trigger payment |
Test data strategy: use the payment provider's own documented test card numbers and test scenarios for the sandbox tier (nearly every major provider publishes specific card numbers that deterministically trigger a decline, an insufficient-funds error, or a timeout), rather than inventing arbitrary fake numbers whose behavior against the real sandbox is unverified. For the E2E tier, seed a dedicated test account and cart state per test run so tests are independent and repeatable, rather than sharing mutable state across test runs.
Mocking vs. sandbox decision: mock the payment provider only at the unit-test layer, where the goal is to test the CLIENT's own decision logic in isolation and a real network call would only slow the test down without adding coverage of anything the client controls. Use the real sandbox at the integration layer specifically because that is where the client's actual serialized requests and the provider's actual response shapes need to agree, a hand-rolled mock of the provider's API can silently drift from the real contract as the provider's API evolves, passing tests against a mock that no longer matches reality.
Optimistic UI update edge cases from WebSocket message delivery: checkout flows that show optimistic UI state (e.g. "processing", then flipping to "confirmed") driven by WebSocket (a persistent, bidirectional connection protocol) events from the backend must handle messages arriving out of order or duplicated, both of which a plain network is free to do. A payment_confirmed event arriving before its own payment_processing event (reordering) must not leave the UI stuck showing "processing" forever once the actual final state has already arrived; the fix is applying incoming events against a state machine keyed by the event's own sequence number or timestamp, not by arrival order, which is the identical failure mode a payment gateway's own server-side webhooks produce and must be tested the same way. A payment provider delivers webhook events (for example charge.succeeded, charge.refunded) with at-least-once delivery: it retries with backoff whenever your endpoint does not answer with a 2xx response quickly enough, and that retry can arrive well after a later event that was delivered successfully on the first attempt. Concretely: your server receives a charge.refunded webhook (the provider's own event timestamp created=1005) and applies it at real time T=2; then, at real time T=30, a retried delivery of an earlier charge.succeeded webhook (created=1000, originally sent at T=0 but not acknowledged in time) finally arrives. A handler that applies whichever webhook it physically received last would incorrectly revert the charge back to "succeeded" after it was already correctly refunded, even though created=1000 is objectively the older event. The fix mirrors the client-side WebSocket case above: key state transitions off the provider's own event timestamp (or an explicit monotonic sequence or version field most gateways include), not off HTTP arrival order. Store the highest created value already applied per resource, and treat any incoming event whose created is less than or equal to that stored value as a no-op, regardless of when the HTTP request physically arrives. This needs its own explicit test case, webhook retried out of order: Input, two webhook payloads for the same resource, created=1000 type charge.succeeded and created=1005 type charge.refunded. Sequence: deliver created=1005 first (applied normally), then deliver created=1000 second (simulating the provider's retry). Expected output: the final stored state is "refunded" (from the created=1005 event), not "succeeded"; the late-arriving created=1000 event is detected as older than what is already applied and becomes a no-op.
A duplicated payment_confirmed event (the same event delivered twice, which most WebSocket reconnect-and-replay logic can produce) must be a no-op the second time, tested by feeding the same event object to the handler twice and asserting the UI state and any downstream side effect (e.g. an analytics ping) only fire once.
Trade-offs and pitfalls
The most common wrong turn is pushing every edge case to the E2E layer because "that's what really happens in production," which produces a slow, flaky suite that re-tests the same client-side decision logic dozens of times through a full browser instead of once at the unit layer. A second pitfall is mocking the payment provider at the integration layer too, which feels faster but stops catching provider API drift entirely, defeating the actual purpose of having an integration layer. On flakiness specifically, at the test-DESIGN level (not diagnosis or quarantine, which is a separate concern from writing the tests in the first place): avoid asserting on wall-clock-dependent intermediate states, pin any time-based logic behind an injectable clock rather than relying on real elapsed time in a test, and assert on the final, stable state reached rather than a transient one that a slow CI (continuous integration) runner might race past.
Explain property-based testing and how it helps discover edge cases in frontend code. Using JavaScript and fast-check, write a property-based test outline (pseudo-code is fine) for a normalizePhoneNumber(input) function to assert invariants across random inputs: different separators, whitespace, unicode digits, leading '+' country codes, very long strings, and null/undefined inputs.
Sample Answer
Direct answer
Property-based testing generates many random inputs and checks that a general INVARIANT (a rule that should hold for every valid input) is never violated, instead of hand-picking a fixed list of example inputs and their expected outputs. For frontend input-normalization code like normalizePhoneNumber, this matters because the input space (arbitrary user-typed or pasted text) is effectively unbounded, and a fixed example list will only ever cover the specific formatting quirks the test author happened to think of, while a property runs hundreds of randomly-generated variations (including ones no author would think to hand-write) against the same invariant every time.
Structured elaboration
The invariants worth asserting for normalizePhoneNumber(input):
- Output shape. The result is always either
null(unusable input) or a string matching^\+?\d+$(an optional leading+followed only by digits), never a string that still contains a stray separator or letter. - Separator-insensitivity. Interleaving a digit sequence with any separator character (space, dash, dot, parentheses) must not change the extracted digit sequence; separators are noise, not signal.
- Leading-plus preservation. A
+country-code prefix survives the same separator noise that surrounds the digits after it. - No-digits input is always rejected. A string made up entirely of whitespace/separators (no digits at all) normalizes to
null. - Unicode-digit equivalence. A string using non-ASCII decimal digits (e.g. Arabic-Indic digits) normalizes to the SAME result as the ASCII-digit equivalent, since a user's device locale should not change whether their phone number is recognized.
- Total robustness.
null,undefined, and very long strings (a pasted document, or a repeated-character attack string) must never throw; they resolve to a defined value (null, or a length-capped rejection).
Worked example (executed with fast-check in JavaScript, not pseudo-code)
const fc = require('fast-check');
function normalizePhoneNumber(input) {
if (input === null || input === undefined || typeof input !== 'string') return null;
let digits = '';
for (const ch of input) {
if (ch >= '0' && ch <= '9' || ch === '+') { digits += ch; continue; }
const zero = [0x0030,0x0660,0x06F0,0x0966,0x09E6,0xFF10].find(z => ch.codePointAt(0) >= z && ch.codePointAt(0) <= z+9);
if (zero !== undefined) digits += String(ch.codePointAt(0) - zero);
// separators and anything else: dropped
}
if (digits.length === 0 || digits.length > 20) return null;
const hasPlus = digits[0] === '+';
const digitsOnly = digits.replace(/\+/g, '');
return digitsOnly.length ? (hasPlus ? '+' : '') + digitsOnly : null;
}
const digit = () => fc.array(fc.constantFrom('0','1','2','3','4','5','6','7','8','9'), {minLength:1,maxLength:15}).map(a=>a.join(''));
fc.assert(fc.property(fc.string({maxLength:30}), s => {
const out = normalizePhoneNumber(s);
return out === null || /^\+?\d+$/.test(out);
})); // invariant 1: output shape
fc.assert(fc.property(fc.tuple(digit(), fc.constantFrom(' ','-','.','(',')')), ([d, sep]) => {
return normalizePhoneNumber(d) === normalizePhoneNumber(d.split('').join(sep));
})); // invariant 2: separator-insensitivity
fc.assert(fc.property(digit(), (d) => {
const arabicIndic = d.split('').map(c => String.fromCodePoint(0x0660 + Number(c))).join('');
return normalizePhoneNumber(d) === normalizePhoneNumber(arabicIndic);
})); // invariant 5: unicode-digit equivalence
console.log(normalizePhoneNumber(null), normalizePhoneNumber(undefined)); // invariant 6
Executed output (ran with numRuns: 500, seed 20260724, against the real fast-check package): all seven property checks in the full scratch suite passed, including the three shown above (output-shape, separator-insensitivity, and unicode-digit-equivalence all reported [PASS] with zero counterexamples found across 500 generated inputs each), plus separately-verified checks for leading-plus preservation, no-digits-rejection, null/undefined handling (both print null), and very-long-string robustness (no exceptions across strings up to 200 characters).
Trade-offs & pitfalls
The biggest pitfall with property-based testing is writing a property that is too weak to catch the bug it's meant to catch, "the function doesn't throw" is a property, but it would not catch a function that always returns the wrong digits without throwing; the properties above are deliberately RELATIONAL (comparing two related inputs' outputs, like the separator-insensitivity check) rather than purely existential, because relational properties are much harder to satisfy by accident. A second pitfall is assuming a passing property-based run means the invariant is proven for all inputs; it is proven only for the inputs the generator actually produced in that run (500 here), which is why a fixed seed matters for reproducibility but does not substitute for occasionally widening the run count or the generator's range during development. Third, unicode-digit handling is easy to under-specify, this implementation intentionally silently DROPS unrecognized unicode digit blocks (rather than guessing), a defensible but not the only valid choice, and that choice should be its own explicit example test, not left implicit in the property.
Implement a reusable debounce utility in JavaScript with options for leading and trailing invocation and a cancel method. Ensure it correctly handles rapid successive calls, retaining 'this' context, and returns the result of the debounced function when appropriate. Provide an ES6 implementation and explain edge cases (e.g., cancel during pending leading call).
Sample Answer
Direct answer
A correct debounce utility needs to track not just a pending timer but how many calls occurred within the current window, because leading-edge and trailing-edge invocation interact: a single call in a leading+trailing window must fire once, not twice, while multiple calls in that same window correctly fire twice (once on the leading edge with the first call's arguments, once on the trailing edge with the last call's arguments). cancel() can only suppress a pending trailing call; it cannot undo a leading call that has already executed synchronously.
Structured elaboration
- Leading vs. trailing semantics: leading invokes immediately on the first call of a new window; trailing invokes once the window elapses with no further calls. Both can be enabled together, which is where most naive implementations get the single-call case wrong (see below).
- The double-invoke trap: a naive implementation that unconditionally fires the trailing call whenever
trailingis true will invoke twice for a window containing exactly one call under{leading: true, trailing: true}, once from the leading edge and once from the trailing edge, for the same logical call. The fix is tracking a per-window call count and suppressing the trailing invocation specifically when the window had exactly one call AND that call already fired on the leading edge. - Retaining
thiscontext: use a regularfunctionexpression for the returned debounced wrapper (not an arrow function) and call the wrapped function withfn.apply(thisArg, args), capturingthisfrom the call site of the debounced wrapper itself, not from wheredebounce()was originally invoked. - Cancel during a pending leading call: if
leading: trueand a call has already fired synchronously, the side effect has already happened, cancel cannot retroactively undo it. Whatcancel()legitimately does is clear the pending timer so the TRAILING call that would otherwise fire later never happens. This distinction (already-happened vs. still-pending) is the actual edge case named in the question, and a test must assert on it precisely: the leading call's effect persists after cancel, only the trailing call is suppressed. - Return value: the debounced function should return whatever the underlying function returned on its most recent actual invocation, since a caller synchronously reading the return value on a leading call needs that value immediately, not after the debounce window closes.
Worked example (executed, ES6/ECMAScript 2015)
function debounce(fn, wait, { leading = false, trailing = true } = {}) {
let timer = null, lastArgs = null, lastThis = null, result, callCountInWindow = 0;
function invoke(args, thisArg) { result = fn.apply(thisArg, args); return result; }
function debounced(...args) {
const isNewWindow = timer === null;
lastArgs = args; lastThis = this; callCountInWindow += 1;
if (isNewWindow && leading) invoke(args, this);
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
const shouldTrailingInvoke = trailing && !(leading && callCountInWindow === 1);
if (shouldTrailingInvoke) invoke(lastArgs, lastThis);
timer = null; callCountInWindow = 0;
}, wait);
return result;
}
debounced.cancel = function () {
if (timer !== null) { clearTimeout(timer); timer = null; callCountInWindow = 0; }
};
return debounced;
}
Run against seven scenarios with real timers (30ms wait, real setTimeout, no mocked clock):
scenario1_trailing_only: ["c"]
scenario2_leading_and_trailing_multi_call: ["a","c"]
scenario3_leading_and_trailing_single_call: ["only"]
scenario4_this_context: fn ran without throwing, retained call succeeded
scenario5_leading_return_value: 10
scenario6_cancel_during_pending_leading: {"callsRightAfterLeadingEdge":["first"],"callsAfterCancelAndWait":["first"]}
scenario7_cancel_noop: no throw, safe
Scenario 2 confirms the multi-call case correctly fires twice (["a","c"], first and last), scenario 3 confirms the single-call case correctly fires exactly once (not ["only","only"]), and scenario 6 confirms the cancel-during-pending-leading-call edge case precisely: first is recorded once (the leading call already ran) and stays at exactly ["first"] after cancel and the wait elapses, meaning the trailing call for second was successfully suppressed and the already-fired leading call was correctly left alone.
Trade-offs and pitfalls
The most common wrong turn is the double-invoke bug described above, which passes any test that only checks "trailing mode alone" and "leading mode alone" separately and never tests the combination on a single-call window. A second pitfall is using an arrow function for the debounced wrapper, which permanently binds this to the enclosing lexical scope at definition time and silently breaks any usage as an object method. A third is assuming cancel() should reset callCountInWindow retroactively affect a leading call that already fired; it should not, and a test asserting the leading call's side effect persists after cancel is the one that actually catches an implementation that got this wrong.
Unlock Full Question Bank
Get access to all 7 Test Case Design and Edge Case Analysis interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.