How to test CLI apps with snapshot stdout
Test CLI output by capturing stdout in a child process and snapshotting it, so refactors do not silently change the user-facing text.
Step-by-step guides and in-depth articles to level up your skills.
Page 5 of 9
Test CLI output by capturing stdout in a child process and snapshotting it, so refactors do not silently change the user-facing text.
Let the browser upload straight to S3 using a short-lived presigned URL, keeping your server out of the data path and saving bandwidth.
Validate checkbox groups for minimum selection and radio groups for required choice, mapping native constraints to clear messages.
Parse and validate the entire config with a schema before the app starts, so a misconfigured instance refuses to boot instead of failing at runtime.
Parse and validate deeply nested form payloads with Zod schemas, surfacing field-level errors without losing the original input shape.
Collect per-field and form-level errors into one structure, order them by severity, and render an accessible error summary that links to each field.
Cancel an in-flight upload with AbortController, clean up the partial server-side artifact, and refund the UI to idle without leaked listeners.
Split a large file into chunks, upload each with its own retry, and resume from the last confirmed chunk after a network drop without restarting.
Make fields required based on another field value using discriminated unions or refine, so the schema encodes the dependency instead of the UI.
Validate rules that span multiple fields like password confirm, date ranges, and conditional billing with a single refine over the whole form.
Debounce async field checks so the server is hit once after typing settles, cancel stale requests, and keep the submit button responsive during checks.
Build an accessible drag-and-drop zone that also works with keyboard and click, validates dropped files, and avoids the common dropoutside bug.
Sniff the real file type from magic bytes instead of trusting the extension or Content-Type, and reject mismatches before storing the upload.
Implement an atomic, sharded counter in Redis with INCR, CRDT merge for partitions, and eventual consistency for global aggregation.
Design an in-process feature flag service with rules, gradual rollouts, and safe overrides that degrade gracefully when the flag store is unavailable.
Deliver webhooks with exponential backoff, jitter, dead-letter queues, and idempotency to handle endpoint failures without losing events.
Version an API by embedding the version in the URL path, with backward-compatible defaults, deprecation headers, and sunset tracking.
Route read queries to replica databases and writes to the primary, with health checks and fallback when replicas lag or fail.
Let clients select specific fields via a fields query parameter, reducing payload size and improving latency for mobile and edge clients.
Authorize every GraphQL resolver with field-level checks, depth limiting, and query cost analysis to prevent data leaks and expensive queries.
Return consistent, machine-readable error objects with a code, message, details, and request ID so clients can handle errors programmatically.
Localize validation messages by passing a message key and parameters to the schema, then resolving them through a translation function at render time.
Validate untrusted request bodies with JSON Schema at the API boundary, reuse the schema for client forms, and evolve it with compatibility checks.
Resume a large upload after a drop by tracking confirmed ranges, re-requesting only the missing part, and verifying the assembled file with a checksum.
Queue multiple uploads with a bounded concurrency, retry each independently, and report per-file and overall progress without blocking the UI thread.
Compose nested Zod schemas for deeply structured forms, discriminate unions, and surface field-level errors with type-safe parse results.
Bundle a Node CLI into a single file with esbuild, mark node deps external, and add a shebang so the output runs as a bin on any machine with Node.
Partition resources like connection pools by tenant or feature so a flood in one cannot starve the others, and a failure stays contained.
Propagate an AbortSignal through async layers so a user cancel stops all in-flight work, and each layer cleans up on abort.
Color CLI output with Chalk to signal severity, keep color optional with a no-color flag, and structure lines so they parse as well as they read.
Wrap a flaky call in a circuit breaker that trips after N failures, half-opens to test recovery, and fails fast instead of queuing doomed calls.
Parse argv with a typed schema so flags become typed values, unknown flags fail, and a usage message prints on a parse error.
Load CLI config from a file with layered overrides for flags and env, validate it with a schema, and fail closed on an invalid config.
Report progress for a long CLI task with a single-line spinner or a bar, throttle redraws, and clear the line on completion for clean logs.
Generate a project scaffold from templates with variable substitution, conditional files, and a post-install hook so the user gets a runnable project.
Structure a CLI with Commander subcommands, share options, and keep help readable as the command tree grows beyond a handful of actions.
Bound concurrency with a pool so you do not trip connection limits or saturate bandwidth, and let the rest queue until a slot opens.
Retry transient failures with backoff, give up after a budget, and render a retry-able error boundary instead of a blank page when the budget is spent.
When a dependency is down, serve a cached or partial result with a banner rather than failing the whole page, and keep the write path honest.
Paginate a GraphQL list with cursors rather than offsets so inserts during paging do not shift the window, using the Relay connection spec.
Expose liveness and readiness probes with different meanings, keep them cheap, and never let them depend on a slow dependency.
Load more as the user scrolls with an IntersectionObserver sentinel, keep the query key stable, and avoid fetching the same page twice on overlapping events.
Add interactive prompts with Inquirer for choices, confirmations, and multi-select, with sensible defaults so the CLI works non-interactively too.
Choose the right claims for a JWT, use registered names like sub and exp, add custom claims for authorization, and keep the payload small and non-sensitive.
Rotate refresh tokens on each use, detect reuse as a theft signal, and keep access tokens short without forcing re-login on every call.
Compare stateless JWT sessions against server-side sessions, weigh revocation and size against lookup cost, and pick based on who verifies and how you log out.
Scope a JWT to a tenant with a tid claim, enforce tenant isolation in every query, and prevent cross-tenant access through a forged or reused token.
Add a code challenge to the OAuth2 authorization code flow so a public client like a SPA cannot have its code intercepted, without a client secret.
Apply a write to the UI before the server confirms, roll back on error, and keep the window small so a failed update does not confuse the user.
Pick a rate limit strategy, fixed window, sliding window, or token bucket, and apply it fairly per caller so one client cannot starve the rest.
Deduplicate in-flight requests by key so concurrent callers share one fetch, cache the result, and avoid doubling load when components mount together.
Retry a transient failure with exponential backoff and jitter, cap the attempts, and classify which errors are worth retrying.
Sign JWTs with RS256 using a key pair, rotate keys with a kid header, and publish the public key in a JWKS endpoint for verifiers.
Split auth into a short access token for API calls and a longer refresh in a cookie, so a stolen access token expires fast and refresh is bound to one origin.
Collapse concurrent identical expensive calls into one in-flight work so the result is computed once and shared with all waiters.
Prefetch data on the server and pass it to the client as dehydrated state, so the first paint is full and the client hydrates without a flash of empty content.
Put the session in a signed JWT so the server keeps no session table, enforce expiry and claims, and accept the trade-off that revocation needs a list.
Use SWR to cache, revalidate, and dedupe fetches in React, with a focus on key design and the revalidate-on-focus policy for fresh data.
Use TanStack Query invalidation to refetch only the queries a mutation touches, with query keys as arrays and partial invalidation by prefix.
Test a CLI by invoking its action with argv and a mock stdout, assert the exit code and output, and avoid spawning a process for every case.
Set per-hop timeouts tighter than the caller budget so a slow leaf does not hold the root, and propagate cancellation up the chain.
Keep a bounded revocation list of jti values to force logout before expiry, prune expired entries, and check it on every verify without a session table.
Wire async validators into React Hook Form, debounce server checks, and resolve field errors without blocking the submit button.
Let the browser upload straight to S3 through a presigned URL so your server never proxies the bytes, with a short-lived PUT and a content-type constraint.
Stream multipart uploads straight to storage without buffering in memory, enforce size limits mid-stream, and abort on limit breach.
Report upload progress with XMLHttpRequest upload.onprogress or fetch with a streaming response, and render a percent without re-rendering on every byte.
Adopt Valibot for tree-shakeable schema validation that ships a fraction of Zod bytes while keeping a comparable ergonomic API.
Define the fields, types and guarantees a producer owes its consumers, enforce the contract in tests, and evolve it without breaking downstream jobs.
Retrieve relevant passages with embeddings, store them in a vector index, and ground LLM answers in cited context rather than guesses.
Extract only what changed since the last run with durable watermarks, handle late data, and make reruns idempotent instead of duplicating rows.
Cache model answers by meaning rather than exact text, set a similarity threshold that bounds false hits, and invalidate entries when prompts or models change.
Choose chunk sizes, overlaps and boundaries that keep retrieved passages meaningful, then measure how each strategy affects recall before committing to one.
Compare live feature and prediction distributions against training baselines, choose tests that catch real drift, and alert only when the shift matters.
Constrain model output to a schema, validate every response before trusting it, and repair or retry invalid payloads without looping forever or hiding failures.
Replace subjective impressions with a versioned set of graded examples, task-appropriate metrics and automated regression tests that run on every prompt change.
Set timeouts that match the task, keep partial output useful when a call fails mid stream, and retry only the work that is safe to repeat.
Make a build produce byte-identical output from the same source, so you can verify an artifact was built from the code you reviewed.
Offer HTTP/3 alongside HTTP/2 with the Alt-Svc header, using a compatible port, migration and fallback so clients upgrade safely.
Name spans and label attributes with OpenTelemetry semantic conventions so traces are consistent and queryable across services and languages.
Automate versioning and publishing from commit messages with semantic-release, using conventional commits and CI release pipelines.
Recognise and prevent deadlocks in async code: lock ordering, bounded waits, transaction scope and cancellation so a stall is impossible or fails fast.
Populate a new column over millions of rows in batches, without long locks, replication lag or a table rewrite.
Extract, normalise, chunk and index documents at scale with stable ids, content hashing and incremental updates that avoid full re-indexing.
Serve consistent features to training and inference by separating offline batch computation from an online low-latency store with point-in-time correctness.
Enforce per-client request limits across many instances with an atomic Redis algorithm that survives restarts and clock skew.
Use Bazel for hermetic, incremental JavaScript builds: BUILD targets, the dependency graph, remote caching and correct globals.
Build a publishable library with Rollup: multiple output formats, external peer deps, type declarations and preserving tree shaking.
Understand where DNS is cached, honour TTLs and negative caching, and avoid re-resolving on every request.
Assign levels by what an operator does with the line, keep structured fields, and control volume so logs stay useful and affordable.
Pick between auto-increment, UUID and time-ordered identifiers by weighing index locality, predictability and uniqueness.
Use esbuild for raw speed and Rollup for optimised output, and combine them so fast development does not cost you bundle quality.
Pick the right isolation level by understanding the anomalies each prevents: dirty reads, lost updates, write skew, phantoms and their costs.
Run an incident with a clear commander, a single channel and regular status updates so responders and stakeholders stay aligned.
Wire receivers, processors and exporters into collector pipelines for traces, metrics and logs, with batching, retries and back-pressure.
Describe task dependencies and cache inputs and outputs so a monorepo build skips work that has not changed.
Proxy WebSocket connections correctly: Upgrade headers, timeouts, sticky routing and scale, so ws:// sockets survive the proxy tier.
Sample CPU and memory profiles across a fleet so you can find the code path behind a latency regression without reproducing it.
Keep time-series storage affordable by limiting label combinations, avoiding unbounded dimensions and aggregating high-cardinality data.
Reduce p99 latency by issuing a second request when the first is slow, taking the first response and cancelling the loser.
Turn reliability goals into measurable service level indicators and error budgets that decide when to ship features and when to stop.