Claude Prompt Library

50 Claude Prompts That Write Your Unit Tests

50 copy-paste prompts

Paste a function, a component, or a failing test and Claude returns runnable test code in your framework: the cases that matter, the fixtures and mocks they need, and the assertions that would actually catch a regression. Prompts for new suites, edge cases, mocking, flaky tests, and coverage gaps.

In short: This page contains 50 copy-paste ready prompts, organized into 5 categories with a description and pro tip for each. The first 5 prompts are free instantly, no signup needed. Hand-curated and tested by the AI Academy team.

By Louis Corneloup ยท Founder, Techpresso
Last updated ยทHand-curated & tested by the AI Academy team

Test Suites From Scratch

10 prompts

Unit Test Suite for a Function

1/50

You are a test engineer who writes tight, readable unit tests that catch real regressions. <context> I have a function with no tests and I want a suite that covers its behavior, not just its happy path, and that runs as-is in my project. </context> <inputs> - Function: [PASTE THE CODE] - Test framework and version: [JEST, VITEST, PYTEST, GO TEST, JUNIT] - What the function is supposed to guarantee: [CONTRACT IN PLAIN WORDS] - Realistic inputs it receives: [WHERE THEY COME FROM AND TYPICAL VALUES] - Anything it depends on: [CLOCK, RANDOM, NETWORK, DATABASE, ENV VARS] </inputs> <task> Write the suite: happy path cases with realistic data, one case per branch in the code, boundary values, invalid input and the error each should produce, and the behavior around any dependency you had to control. Group them with clear describe blocks, name each test after the behavior it asserts, and assert on outcomes rather than on how the function got there. Then list the cases you deliberately left out and why. </task> <constraints> - Runnable code in the framework I named, with imports and setup included. - One behavior per test and no shared mutable state between tests. - No assertions on internal calls unless the call itself is the contract. </constraints> <format> Return the complete test file in an artifact, then a short table of case, why it matters, and what breaking change it would catch. </format>

Writes a complete, runnable unit test suite for one function with branch, boundary, and error cases.

๐Ÿ’ก

Pro tip: Describe the contract in plain words first. Claude writes tests that match your intent instead of tests that just re-describe the current code.

Service Class Test Suite

2/50

You are a test engineer who tests service classes with injected dependencies. <context> I have a class that coordinates other things (repositories, clients, a queue) and I need tests that verify its logic without standing up the whole system. </context> <inputs> - Class code: [PASTE] - Framework and mocking library: [E.G. VITEST WITH VI.MOCK, PYTEST WITH MONKEYPATCH] - Dependencies and how they are injected: [CONSTRUCTOR, CONTAINER, IMPORTED MODULE] - Business rules it enforces: [WHAT MUST AND MUST NOT HAPPEN] - Side effects worth asserting: [EMAILS SENT, EVENTS PUBLISHED, ROWS WRITTEN] </inputs> <task> Write the suite: one test per business rule, tests for the orchestration order where order matters, tests for how failures in each dependency are handled (throws, retries, partial state), and tests that the declared side effects happen exactly once with the right payload. Include the setup that builds the class with test doubles and a helper to construct it with overrides. </task> <constraints> - Mock only at the boundary of the class: do not mock the class under test. - Assert on payloads and counts of side effects, not merely that a stub was called. - Keep each test readable without scrolling: extract setup into named helpers. </constraints> <format> Return the test file plus the construction helper in an artifact, then the list of rules covered mapped to test names. </format>

Tests a service class rule by rule, including dependency failures and exact side-effect payloads.

๐Ÿ’ก

Pro tip: List the side effects that matter. Asserting the exact email payload catches bugs that "was called once" assertions sail straight past.

API Route Handler Test Suite

3/50

You are a backend test engineer who tests HTTP handlers end to end at the request level. <context> I want tests that hit my endpoint with real requests and assert on status codes, bodies, and side effects, without needing a browser or a deployed environment. </context> <inputs> - Handler code: [PASTE THE ROUTE] - Framework and test tooling: [EXPRESS WITH SUPERTEST, NEXT ROUTE HANDLER, FASTAPI TESTCLIENT, RAILS REQUEST SPEC] - Auth requirement: [PUBLIC, USER, ADMIN, HOW TO FAKE IT IN TESTS] - Request shapes: [VALID BODY, QUERY PARAMS, HEADERS] - What it persists or calls: [DATABASE, EXTERNAL API] </inputs> <task> Write tests for: the success case with the full response body asserted, each validation failure with its status code and error shape, unauthenticated and wrong-user access, a not-found case, a conflict or duplicate case, and the failure mode when the external dependency errors or times out. Include the request helper, auth fixture, and the database or mock setup and teardown. </task> <constraints> - Assert status code and response body shape in every test, not one or the other. - Include one test proving another user cannot access the resource. - Reset state between tests so the file passes in any order. </constraints> <format> Return the test file with helpers in an artifact, then a coverage table of status code, scenario, and assertion. </format>

Writes request-level tests for an endpoint covering validation, auth, conflicts, and dependency failures.

๐Ÿ’ก

Pro tip: Insist on an unauthorized-access test for every resource endpoint. It is the cheapest permanent guard against the IDOR bugs reviews miss.

React Component Test Suite

4/50

You are a frontend test engineer who tests components the way a user experiences them. <context> I need tests for a component that assert what the user sees and can do, and that do not break every time I refactor the markup. </context> <inputs> - Component code: [PASTE, INCLUDING ITS PROPS AND HOOKS] - Tooling: [REACT TESTING LIBRARY WITH JEST OR VITEST, TESTING LIBRARY VERSION] - States it can be in: [LOADING, EMPTY, ERROR, SUCCESS, DISABLED] - User interactions: [CLICKS, TYPING, SUBMIT, KEYBOARD] - External calls or context it needs: [FETCH, ROUTER, PROVIDERS, STORE] </inputs> <task> Write tests for each state, each interaction and its visible outcome, the loading-to-loaded transition, error rendering when the request fails, form validation messages, and the accessible name and role of the interactive elements. Include the render helper that wraps the component in its providers, the request mocking setup, and user-event based interactions. </task> <constraints> - Query by role, label, and text: no test ids unless nothing else identifies the element. - Never assert on internal state, hook calls, or class names. - Await user interactions and assert with the async matchers so tests do not race the render. </constraints> <format> Return the test file plus the render helper in an artifact, then a table of state or interaction and the user-visible assertion. </format>

Writes user-facing component tests for every state and interaction using role and label queries.

๐Ÿ’ก

Pro tip: List the states the component can be in, including empty. Empty and error states are where untested components fail in front of users.

Characterization Tests for Legacy Code

5/50

You are an engineer who makes untested legacy code safe to change. <context> I have to modify old code with no tests. Before touching it I want tests that lock in what it does today, bugs included, so I notice any change I did not intend. </context> <inputs> - Legacy code: [PASTE] - Language and framework: [INCLUDING VERSION QUIRKS] - Real inputs I can supply: [SAMPLE PAYLOADS, ROWS, FILES] - Dependencies that make it hard to test: [GLOBALS, CLOCK, DATABASE, NETWORK, STATIC CALLS] - The change I need to make afterwards: [MY ACTUAL TASK] </inputs> <task> Design characterization tests that pin current behavior: pick inputs that exercise each distinct path, record the current output as the expected value, and cover the odd behaviors that look wrong but may be relied upon. Where a dependency blocks testing, give the smallest seam to introduce (parameter, injected clock, wrapper) with the exact edit. Then say which tests will fail once I make my intended change, so I know which failures are expected. </task> <constraints> - Do not fix bugs while writing these tests: pin the behavior as it is and note it. - Prefer the smallest seam over a refactor: I have to ship a change. - Mark each expected value as verified-by-running or assumed, so I run them once before trusting them. </constraints> <format> Return the seam edits, the test file, then the list of tests expected to change when my edit lands. </format>

Pins existing legacy behavior in tests, adds minimal seams, and flags which tests your change should break.

๐Ÿ’ก

Pro tip: Run the generated tests before trusting them. Characterization tests are only useful once the expected values come from the real code, not from a guess.

Test Plan From Acceptance Criteria

6/50

You are a test architect who turns requirements into a test plan before any code exists. <context> I am about to build a feature and I want the test cases written first, so implementation aims at them instead of the reverse. </context> <inputs> - Feature and acceptance criteria: [PASTE THE TICKET] - Where the logic will live: [FUNCTION, SERVICE, ENDPOINT, COMPONENT] - Framework and test levels available: [UNIT, INTEGRATION, END TO END] - Data and dependencies involved: [TABLES, EXTERNAL SERVICES] - Non-functional requirements: [LIMITS, PERMISSIONS, PERFORMANCE] </inputs> <task> Turn each acceptance criterion into concrete test cases with named inputs and expected outcomes, then add the cases the ticket forgot: invalid input, permission boundaries, concurrent use, empty and maximum data, and failure of each dependency. Assign every case to the cheapest level that can catch it and justify anything you put at the end-to-end level. Then write the unit test skeletons with descriptive names and failing assertions ready to fill in. </task> <constraints> - Every case names a specific input and a specific expected outcome, not a topic. - Push cases down to the cheapest level: end-to-end only where nothing else can cover it. - Flag any acceptance criterion too vague to test and write the question to resolve it. </constraints> <format> Return the case table (criterion, input, expected, level), then the failing test skeletons in an artifact. </format>

Converts acceptance criteria into a leveled test case table plus failing test skeletons to build against.

๐Ÿ’ก

Pro tip: Ask which criteria are too vague to test. Those are the ones that come back as bugs after release because nobody agreed on the behavior.

Reducer and State Machine Test Suite

7/50

You are a test engineer who tests state transitions exhaustively. <context> I have a reducer, store, or state machine and I want confidence that every transition and every invalid transition behaves correctly. </context> <inputs> - Code: [PASTE THE REDUCER, MACHINE, OR STORE] - Framework: [REDUX, ZUSTAND, XSTATE, PLAIN REDUCER, TEST RUNNER] - States and events: [LIST THEM IF THE CODE IS LONG] - Illegal transitions: [WHAT MUST NEVER HAPPEN] - Side effects attached to transitions: [EFFECTS, LISTENERS, PERSISTENCE] </inputs> <task> Build a transition matrix of state by event, then write tests for every cell: the resulting state and payload for legal transitions, and unchanged state or a thrown error for illegal ones. Add tests for the initial state, sequences of events that reach deep states, idempotent repeat events, and that reducers do not mutate the previous state object. Cover the side effects separately from the state result. </task> <constraints> - Assert the whole next state, not one field, so unexpected changes fail the test. - Include a test that the previous state object is not mutated. - Drive multi-step cases by replaying a list of events rather than hand-building state. </constraints> <format> Return the transition matrix, then the test file in an artifact, then the transitions you found that the code does not handle at all. </format>

Builds a full state-by-event transition matrix and tests every legal and illegal transition, mutation included.

๐Ÿ’ก

Pro tip: Ask for the unhandled transitions. The gaps in the matrix are usually real bugs that no amount of happy-path testing exposes.

CLI Command Test Suite

8/50

You are a test engineer who tests command line tools. <context> I have a CLI command and I want tests covering its arguments, output, and exit codes without spawning a real shell for every case. </context> <inputs> - Command code: [PASTE THE COMMAND AND ITS ARG PARSING] - Framework: [COMMANDER, YARGS, CLICK, COBRA, TEST RUNNER] - Arguments and flags: [REQUIRED, OPTIONAL, DEFAULTS] - Side effects: [FILES WRITTEN, NETWORK CALLS, PROCESS EXIT] - Output contract: [HUMAN TEXT, JSON MODE, QUIET MODE, STDERR USAGE] </inputs> <task> Write tests for: valid invocations and their stdout, missing and invalid arguments with the usage message and non-zero exit code, flag defaults and overrides, conflicting flags, the JSON output mode being parseable, errors going to stderr while data goes to stdout, and interrupted or partial runs. Refactor the entry point so the command logic is callable in-process with injected streams, and show that edit. </task> <constraints> - Test the command function in-process with captured streams: no real process spawning except one smoke test. - Assert exit codes explicitly in every failure case. - Keep filesystem effects inside a temporary directory created and removed per test. </constraints> <format> Return the entry point edit, the test file in an artifact, then a table of invocation, exit code, and expected output. </format>

Tests a CLI in-process for flags, exit codes, stdout versus stderr, and JSON output with temp-dir isolation.

๐Ÿ’ก

Pro tip: Ask for the in-process seam first. Spawning the binary per test makes suites slow and makes assertion failures nearly impossible to debug.

Validation Schema Test Suite

9/50

You are a test engineer who tests input validation schemas. <context> My validation schema is the boundary between untrusted input and my code, and I want proof it accepts what it should and rejects everything else. </context> <inputs> - Schema: [PASTE THE ZOD, YUP, JOI, PYDANTIC, OR DTO DEFINITION] - Test framework: [NAME AND VERSION] - The real payloads it validates: [SAMPLE VALID INPUT] - Rules that matter most: [REQUIRED FIELDS, FORMATS, RANGES, ENUMS, DEPENDENT FIELDS] - What happens on failure: [ERROR SHAPE RETURNED TO THE CLIENT] </inputs> <task> Write tests that accept a canonical valid payload and each valid variant (optional fields absent, alternative shapes), then reject: missing required fields, wrong types, out-of-range numbers, malformed strings, invalid enum values, extra unexpected keys, empty strings versus null, and values that pass one rule but violate a cross-field rule. Assert the error path and message for each rejection, and test coercion and defaults produce exactly the parsed output you expect. </task> <constraints> - Assert on the parsed output for valid cases, not just that validation passed. - Every rejection test asserts which field failed and why. - Include one payload with unexpected extra keys and state whether they are stripped or rejected. </constraints> <format> Return the test file in an artifact, then a table of case, verdict, and error path, then the rules your schema does not enforce yet. </format>

Tests a validation schema against valid variants and every rejection case, asserting parsed output and error paths.

๐Ÿ’ก

Pro tip: Assert the parsed output, not just success. Coercion and default rules quietly change values and only output assertions catch it.

Repository and Data Access Test Suite

10/50

You are a test engineer who tests data access code against a real database. <context> I want tests for my repository layer that catch query mistakes, which mocked database tests never do, while still running fast and in isolation. </context> <inputs> - Repository code: [PASTE THE QUERIES OR ORM METHODS] - Database and access layer: [POSTGRES WITH PRISMA, SQLALCHEMY, ACTIVERECORD, ETC] - Test database available: [DOCKER CONTAINER, SQLITE, TRANSACTIONAL FIXTURES] - Schema and constraints: [TABLES, UNIQUE KEYS, FOREIGN KEYS, DEFAULTS] - Behaviors that matter: [FILTERING, SORTING, PAGINATION, SOFT DELETE, TENANT SCOPE] </inputs> <task> Write tests for: create with defaults applied, read with each filter combination, update of partial fields, delete or soft delete visibility, unique constraint violations surfacing as the error my code expects, foreign key behavior on cascade, ordering and pagination correctness at page boundaries, and that queries never return rows from another owner or tenant. Include per-test isolation via transaction rollback and a seed helper. </task> <constraints> - Use a real database, not mocks: the point is to test the query. - Each test rolls back so the suite is order independent and can run in parallel. - Seed only the rows a test needs, including one row that must not be returned. </constraints> <format> Return the isolation setup, the seed helper, the test file in an artifact, then the queries you consider still under-tested. </format>

Tests repository queries against a real database with transaction rollback isolation and negative-row seeding.

๐Ÿ’ก

Pro tip: Always seed a row that must not come back. A query missing its owner filter passes every test until a foreign row exists to prove it.

XML tags are just the start. Learn the full Claude workflow.

A growing library of 300+ hands-on AI tutorials covering Claude, ChatGPT, and 50+ tools. New tutorials added every week.

Start 7-Day Free Trial

Edge-Case & Boundary Tests

10 prompts

Edge Case Enumeration From a Signature

11/50

You are a test designer who enumerates everything that can go wrong with a function before writing a single test. <context> I want the list of cases worth testing for this function, ranked, so I can spend my time on the ones that would actually catch a bug. </context> <inputs> - Function signature and body: [PASTE] - Where its inputs come from: [USER FORM, API, DATABASE, ANOTHER SERVICE] - What it is used for in the product: [BUSINESS MEANING] - Cost of it being wrong: [MINOR GLITCH / WRONG INVOICE / DATA LOSS] - Existing tests: [PASTE OR SAY NONE] </inputs> <task> For each parameter, enumerate equivalence classes and boundaries, then combine them into cases where interaction matters. Add cases from the code itself: every branch, every early return, every thrown error, every loop that can iterate zero times. Rank the resulting list by probability of occurring in production multiplied by damage if wrong, and mark which of my existing tests already cover each one. </task> <constraints> - Do not write test code yet: this is case selection only. - Each case is a specific input, not a category label. - Cap the list at 25 cases and cut the rest explicitly, saying why they are not worth it. </constraints> <format> Return a ranked case table (input, expected, why it matters, already covered), then the five cases to write first. </format>

Enumerates and ranks the edge cases worth testing for one function, marking which existing tests already cover them.

๐Ÿ’ก

Pro tip: Run this before generating tests. Case selection first produces a small suite that catches bugs instead of 40 tests that all cover the same branch.

Boundary Value Test Table

12/50

You are a test engineer who specializes in boundary testing. <context> My function has limits, ranges, or thresholds and I want tests exactly at, just below, and just above each one. </context> <inputs> - Code: [PASTE THE FUNCTION] - Limits and their meaning: [E.G. MAX 100 ITEMS, MIN AGE 18, FREE TIER UP TO 3 PROJECTS] - Inclusive or exclusive at each limit: [WHAT THE BUSINESS RULE ACTUALLY SAYS] - Framework: [TEST RUNNER AND PARAMETERIZED TEST SYNTAX] - Types involved: [INTEGERS, FLOATS, DATES, STRING LENGTHS, ARRAY SIZES] </inputs> <task> For every threshold, produce the boundary set: one below, exactly at, one above, plus zero, negative, and the type maximum where relevant. State the expected result for each from the business rule, not from the code, so a wrong implementation fails. Then write them as one parameterized test per threshold with a readable case name, and separately list any boundary where the code and the stated rule disagree. </task> <constraints> - Derive expected values from the rule I gave you, never from reading the implementation. - Say inclusive or exclusive explicitly for every threshold in the test names. - Include the float and rounding boundary if the value is not an integer. </constraints> <format> Return the boundary table, the parameterized test code in an artifact, then the code-versus-rule mismatches you found. </format>

Generates below, at, and above cases for every threshold and flags where code disagrees with the stated rule.

๐Ÿ’ก

Pro tip: State the business rule separately from the code. That is what lets the generated tests fail on a real off-by-one instead of enshrining it.

Empty, Null and Missing Input Tests

13/50

You are a test engineer who tests the absence of data. <context> My code handles populated data well and behaves unpredictably when things are empty, null, or absent, which is exactly what production sends. </context> <inputs> - Code: [PASTE] - Language and type strictness: [E.G. TYPESCRIPT STRICT, PYTHON, GO] - Fields that can legitimately be absent: [OPTIONAL COLUMNS, PARTIAL PAYLOADS, LEGACY ROWS] - Intended behavior when data is missing: [DEFAULT, SKIP, THROW, RETURN EMPTY] - Framework: [TEST RUNNER] </inputs> <task> Write tests for each flavor of nothing: undefined, null, empty string, whitespace-only string, zero, false, empty array, empty object, array of empty items, missing key versus key set to null, and a deeply nested optional that is absent. Assert the behavior I specified for each, including which ones must throw. Then flag any case where the current code returns a value that is wrong rather than throwing, because those are the dangerous ones. </task> <constraints> - Treat zero, false, and empty string as distinct cases from null: never lump them together. - Assert the exact error type and message where throwing is expected. - Mark silent-wrong-answer cases separately from crash cases. </constraints> <format> Return the test file in an artifact, then a table of empty value, expected, actual today, and severity. </format>

Tests every flavor of missing data separately and separates silent wrong answers from crashes.

๐Ÿ’ก

Pro tip: Keep zero, false, and empty string as separate cases. Falsy-value bugs are the single most common family in JavaScript and Python code.

Unicode and Long Input Tests

14/50

You are a test engineer who breaks string handling with real-world text. <context> My code processes names, messages, or search terms, and users type things my test data never contains. </context> <inputs> - Code: [PASTE THE STRING HANDLING] - What the strings represent: [NAMES, ADDRESSES, MESSAGES, SLUGS, SEARCH QUERIES] - Operations performed: [LENGTH LIMITS, TRUNCATION, UPPERCASING, SLUGIFY, SEARCH, STORAGE] - Storage and display: [DB COLUMN AND COLLATION, HTML, PDF, EMAIL, CSV] - Framework: [TEST RUNNER] </inputs> <task> Write tests using: accented characters, non-Latin scripts, right-to-left text, emoji including multi-codepoint sequences, combining characters, zero-width and control characters, leading and trailing whitespace, a string at exactly the column limit and one above it, and a very long single-word input. Assert correct truncation on character boundaries rather than bytes, correct case transformation for non-English text, preserved round-trip through storage, and safe output in each destination I listed. </task> <constraints> - Include at least one grapheme cluster that breaks naive length and slice operations. - Assert round-trip equality after save and load, not just that the operation ran. - Cover the CSV and email destinations if I listed them, not only HTML. </constraints> <format> Return the test file with the string fixtures in an artifact, then a table of input, operation, expected, and the failure it prevents. </format>

Tests string handling against emoji, non-Latin scripts, and length limits with round-trip and truncation assertions.

๐Ÿ’ก

Pro tip: Ask for a multi-codepoint emoji fixture. Truncating on code units instead of graphemes is the bug that ships broken characters to users.

Money and Precision Test Cases

15/50

You are a test engineer who writes tests for monetary and numeric precision. <context> My code calculates prices, taxes, or payouts and I need tests that would catch a cent going missing. </context> <inputs> - Code: [PASTE THE CALCULATION] - Representation: [INTEGER CENTS, DECIMAL LIBRARY, FLOAT, DB COLUMN TYPE] - Rules: [TAX RATE AND ROUNDING, DISCOUNT ORDER, FEE SPLIT, CURRENCY] - Invariants: [LINE ITEMS SUM TO TOTAL, SPLITS SUM TO THE WHOLE, NO NEGATIVE TOTALS] - Framework: [TEST RUNNER] </inputs> <task> Write tests using values that expose precision problems: amounts producing repeating decimals, a total divided three ways, percentage discounts on odd cents, tax applied before versus after a discount, a currency with zero decimals, very large totals, and a refund that must exactly reverse a charge. Assert the invariants I listed after every operation, and add a property-style test that a random set of line items always sums to the stated total. </task> <constraints> - Use exact expected values written out to the cent, not approximate matchers. - Every test asserts at least one invariant in addition to the returned value. - Include one reconciliation test over a batch of transactions. </constraints> <format> Return the test file in an artifact, then a table of case, expected total, and the invariant it protects. </format>

Writes money tests with exact cent expectations, split residuals, and invariant plus reconciliation checks.

๐Ÿ’ก

Pro tip: Include the three-way split case. Any code that rounds each share independently fails it, and that failure is a real accounting discrepancy.

Date, Timezone and DST Test Cases

16/50

You are a test engineer who writes date tests that fail in the right places. <context> My date logic passes in my timezone and I need tests that would catch the bugs users in other regions hit. </context> <inputs> - Code: [PASTE THE DATE LOGIC] - Date library and framework: [LUXON, DAYJS, NATIVE, PYTHON DATETIME, TEST RUNNER] - Business rules: [E.G. A DAY ENDS AT MIDNIGHT LOCAL, BILLING RENEWS MONTHLY, REPORTS ARE UTC] - Where dates come from and go: [USER INPUT, DB COLUMN TYPE, API FORMAT] - Whether tests can control the clock: [FAKE TIMERS AVAILABLE?] </inputs> <task> Write tests covering: a user in UTC+13 and one in UTC-8 on the same instant, the spring-forward missing hour and the fall-back repeated hour, a monthly renewal from January 31, February 29 in a leap year, the last second of a day and the first second of the next, a date-only value crossing a timezone boundary, and a stored UTC timestamp displayed in local time. Pin the clock in every test and assert both the instant and the human-readable rendering. </task> <constraints> - Freeze the clock explicitly: no test may depend on when it runs. - Set the timezone per test rather than relying on the machine setting. - Assert both the stored instant and the formatted output, since bugs hide in the conversion. </constraints> <format> Return the test file with clock and timezone setup in an artifact, then a table of scenario, timezone, expected value, and the bug it catches. </format>

Writes clock-pinned date tests for timezone extremes, DST transitions, month ends, and leap years.

๐Ÿ’ก

Pro tip: Have the tests set the timezone explicitly. A suite that only passes because your laptop is on one timezone is worse than no date tests at all.

Error Path and Exception Tests

17/50

You are a test engineer who tests failure behavior as carefully as success behavior. <context> My tests prove the code works. I have nothing proving it fails correctly, which is what actually matters at 3am. </context> <inputs> - Code: [PASTE THE FUNCTION AND ITS ERROR HANDLING] - Error contract: [ERROR TYPES, CODES, MESSAGES CALLERS DEPEND ON] - Failure sources: [VALIDATION, NETWORK, TIMEOUT, DATABASE, THIRD PARTY] - Expected behavior per failure: [THROW, RETRY, FALLBACK, PARTIAL RESULT] - Framework and mocking tools: [NAMES] </inputs> <task> Write tests that force each failure: a dependency throwing, a timeout, a malformed response, a rejected promise with a non-error value, and a failure halfway through a multi-step operation. Assert the error type, the code or message callers rely on, that the original cause is preserved, that retries happen the exact number of times with the expected backoff, that no partial state is left behind, and that cleanup runs. Include one test that the error is not swallowed. </task> <constraints> - Assert on error type and code, never only that something was thrown. - Verify retry counts and cleanup calls explicitly. - Include a test proving state is unchanged after a mid-operation failure. </constraints> <format> Return the test file in an artifact, then a table of failure injected, expected behavior, and the assertion that proves it. </format>

Forces every failure mode and asserts error types, retry counts, cleanup, and absence of partial state.

๐Ÿ’ก

Pro tip: Add the mid-operation failure test. Partial writes surviving a failure cause the data inconsistencies that take days to untangle.

Property-Based Test Suite

18/50

You are a property-based testing expert. <context> Instead of guessing individual inputs, I want tests that assert properties over generated inputs and let the tool find the counterexample. </context> <inputs> - Code: [PASTE THE FUNCTION] - Library available: [FAST-CHECK, HYPOTHESIS, PROPTEST, JQWIK] - Properties I believe hold: [E.G. PARSE THEN FORMAT RETURNS THE INPUT, SORTING IS STABLE] - Valid input domain: [TYPES, RANGES, WHAT IS EXCLUDED] - Known invariants: [OUTPUT ALWAYS SORTED, TOTAL ALWAYS POSITIVE, IDEMPOTENT] </inputs> <task> Identify the properties actually worth testing here: round trips, idempotence, invariants that hold for all inputs, commutativity, comparisons against a simpler reference implementation, and metamorphic relations (how the output must change when the input changes in a known way). Write generators constrained to my valid domain, then the property tests with shrinking enabled. Explain what a failure of each property would mean. </task> <constraints> - Constrain generators to realistic inputs: no testing behavior on impossible values. - Include at least one round trip and one reference-comparison property if they apply. - Keep runs bounded so the suite stays fast in CI, and say the run count you chose. </constraints> <format> Return the generators and property tests in an artifact, then a table of property, meaning, and what a counterexample would reveal. </format>

Writes constrained generators and property tests covering round trips, invariants, and metamorphic relations.

๐Ÿ’ก

Pro tip: Ask for a reference-implementation property. Comparing against a slow, obviously-correct version finds bugs no hand-written case would suggest.

Idempotency and Ordering Tests

19/50

You are a test engineer who tests repeated and out-of-order operations. <context> My system receives retries and events that arrive out of order, and I need tests proving that does not corrupt state. </context> <inputs> - Code: [PASTE THE HANDLER OR OPERATION] - Delivery guarantees: [AT LEAST ONCE? ORDERING GUARANTEED?] - Operations and their effects: [WHAT WRITES WHAT] - Idempotency mechanism today: [KEY, VERSION, UNIQUE CONSTRAINT, NONE] - Framework and database access in tests: [NAMES] </inputs> <task> Write tests that: apply the same operation twice and assert the end state and side-effect count are identical to applying it once, apply two events in reverse order and assert the newer one wins, apply an older event after a newer one and assert it is ignored, run two operations concurrently and assert only one succeeds where that is the rule, and replay a full sequence twice and compare final state. Assert side-effect counts, not only stored rows. </task> <constraints> - Count side effects explicitly: emails, webhooks, and charges must not double. - Include a stale-event test, not just a duplicate-event test. - Where the code cannot pass, say what mechanism it needs rather than weakening the test. </constraints> <format> Return the test file in an artifact, then a table of scenario, expected end state, and the mechanism the code relies on to get there. </format>

Tests duplicate, stale, and concurrent operations for idempotent end state and non-duplicated side effects.

๐Ÿ’ก

Pro tip: Assert the number of side effects, not just the final row. Double-charging is invisible in a state assertion and obvious in a call count.

Pagination and Sorting Boundary Tests

20/50

You are a test engineer who tests list endpoints and their edges. <context> My paginated list works on page one and does strange things at the edges: duplicates, skipped rows, or wrong totals. </context> <inputs> - Code: [PASTE THE QUERY AND HANDLER] - Pagination style: [OFFSET AND LIMIT, CURSOR, KEYSET] - Sort options: [FIELDS AND WHETHER THEY ARE UNIQUE] - Filters supported: [WHAT USERS CAN COMBINE] - Framework and test database: [NAMES] </inputs> <task> Write tests for: an empty result set, fewer rows than one page, exactly one full page, an exact multiple of the page size, the final partial page, a page beyond the end, page size zero and above the maximum, a non-unique sort field producing stable ordering, sorting on a nullable field, a row inserted between two page fetches, a row deleted between fetches, and totals matching the number of rows actually returned across all pages. Seed enough rows to make each case meaningful. </task> <constraints> - Include a tie-breaker assertion on non-unique sort fields: instability is the usual duplicate-row bug. - Walk every page in one test and assert the union has no duplicates and no gaps. - Assert the reported total against the walked count. </constraints> <format> Return the seed helper and test file in an artifact, then a table of case, expected rows, and the bug it catches. </format>

Tests pagination edges, unstable sorts, and mid-fetch mutations with a full-walk duplicate and gap assertion.

๐Ÿ’ก

Pro tip: Sort on a non-unique field in one test. Missing tie-breakers duplicate and skip rows across pages, and no single-page test can reveal it.

Mocking & Fixtures

10 prompts

Mock an HTTP Client Cleanly

21/50

You are a test engineer who isolates code from the network without making tests lie. <context> My code calls an external API and my tests either hit the real service or use a mock that no longer resembles it. </context> <inputs> - Code that makes the calls: [PASTE] - HTTP layer: [FETCH, AXIOS, REQUESTS, HTTPX] - Mocking tool available: [MSW, NOCK, RESPONSES, VCR, MANUAL STUB] - Real responses: [PASTE ONE SUCCESS AND ONE ERROR BODY] - Failure modes to cover: [4XX, 5XX, TIMEOUT, MALFORMED JSON, RATE LIMIT] </inputs> <task> Set up interception at the network layer rather than replacing my client, so my request-building code is still exercised. Write handlers for the success response, each error status, a timeout, a malformed body, and a rate-limit response with a retry-after header. Then write tests asserting my code sends the right method, path, headers, and body, and handles each response correctly. Include a strict mode that fails the test on any unmocked request. </task> <constraints> - Base the fixtures on the real bodies I pasted: do not invent fields. - Assert the outgoing request, not just the handling of the response. - Fail loudly on unmocked calls so a new dependency cannot slip through silently. </constraints> <format> Return the mock setup and the test file in an artifact, then a table of scenario, mocked response, and expected behavior. </format>

Sets up network-level HTTP interception with real response fixtures and tests both request and error handling.

๐Ÿ’ก

Pro tip: Paste real response bodies. Mocks built from imagination pass forever and fail the moment your code meets the actual API.

Test Data Factory Builders

22/50

You are a test infrastructure engineer who kills fixture duplication. <context> Every test in my suite builds the same objects by hand, so adding a required field breaks 40 tests and each test is buried in irrelevant setup. </context> <inputs> - Entity shapes: [PASTE THE TYPES, MODELS, OR SCHEMAS] - Framework and language: [NAMES AND VERSIONS] - Relationships: [WHAT REFERENCES WHAT, REQUIRED VERSUS OPTIONAL] - Example test setup today: [PASTE ONE MESSY TEST] - Uniqueness needs: [EMAILS, SLUGS, IDS THAT MUST NOT COLLIDE] </inputs> <task> Write factory builders with sensible defaults, per-call overrides, deterministic but unique values for constrained fields, and helpers for common states (a paid user, an expired subscription, an archived record). Support building related graphs in one call. Then rewrite my messy example test using the factories so only the data relevant to the assertion is visible, and show how to add a new required field in one place. </task> <constraints> - Defaults must produce a valid entity that satisfies every constraint. - Overrides must merge deeply, not replace nested objects wholesale. - Keep values deterministic per test run so failures are reproducible. </constraints> <format> Return the factory module in an artifact, then the rewritten example test, then a usage cheat sheet for the common states. </format>

Builds override-friendly test data factories with named states and rewrites a messy test to use them.

๐Ÿ’ก

Pro tip: Ask for named states like paidUser or expiredTrial. They read like the scenario, which is what makes a test file skimmable months later.

Database Seed and Teardown Fixtures

23/50

You are a test infrastructure engineer who makes database tests fast and isolated. <context> My database tests leak state into each other, fail when run in a different order, and get slower every month. </context> <inputs> - Stack: [DATABASE, ORM, TEST RUNNER] - Current setup: [PASTE YOUR BEFORE AND AFTER HOOKS] - Schema size: [NUMBER OF TABLES, ANY HEAVY REFERENCE DATA] - Parallelism wanted: [SEQUENTIAL OR PARALLEL WORKERS] - Reference data that every test needs: [PLANS, ROLES, COUNTRIES, ETC] </inputs> <task> Design the isolation strategy: transaction rollback per test where the code allows it, truncation with identity reset where it does not, and a per-worker database or schema for parallel runs. Load static reference data once per run and dynamic data per test. Give the exact hooks, the migration-on-startup step, and a guard that refuses to run against a non-test database. Then say how to keep the suite fast as the schema grows. </task> <constraints> - Tests must pass in any order and in parallel after your change. - Include a hard safety check on the database name or URL before any destructive operation. - Do not reset the whole schema between tests if a cheaper strategy works: justify your choice. </constraints> <format> Return the fixture setup code in an artifact, then a table of strategy, cost per test, and when to use it. </format>

Designs transaction, truncation, or per-worker isolation for database tests with a non-test-database safety guard.

๐Ÿ’ก

Pro tip: Insist on the database-name guard. Every team that skips it eventually truncates a real database from a mistyped environment variable.

Fake Clock and Timer Control

24/50

You are a test engineer who removes time from the equation. <context> My code depends on the current time, delays, timeouts, or intervals, and my tests are slow, flaky, or both because of it. </context> <inputs> - Code: [PASTE THE TIME-DEPENDENT LOGIC] - Time usage: [NOW, SETTIMEOUT, INTERVALS, DEBOUNCE, TTL, SCHEDULING] - Framework and fake timer tool: [JEST FAKE TIMERS, VITEST, SINON, FREEZEGUN] - What I need to assert: [EXPIRY, RETRY DELAY, DEBOUNCE, RATE WINDOW] - Async work involved: [PROMISES INSIDE TIMERS?] </inputs> <task> Replace real time with a controllable clock: show the seam if the code calls the clock directly, then write tests that set a fixed now, advance time by an exact amount, and assert what happened at each step. Cover expiry exactly at the boundary and one millisecond either side, a debounce that must fire once for a burst of calls, a retry sequence with backoff, and an interval that must stop on cleanup. Handle promises that resolve inside advanced timers. </task> <constraints> - No real waiting anywhere: the suite must not get slower as delays grow. - Restore real timers after every test so unrelated tests are unaffected. - Flush pending promises after advancing time, and show that explicitly. </constraints> <format> Return the clock seam, the test file in an artifact, then a table of time advanced and expected state at each step. </format>

Injects a controllable clock and tests expiry, debounce, backoff, and intervals with zero real waiting.

๐Ÿ’ก

Pro tip: Ask how to flush promises after advancing timers. Skipping that step is why fake-timer tests appear to do nothing and pass anyway.

Filesystem and Environment Mocks

25/50

You are a test engineer who isolates code from disk and configuration. <context> My code reads files and environment variables, so tests behave differently on my machine, in CI, and on a teammate laptop. </context> <inputs> - Code: [PASTE THE FILE AND CONFIG ACCESS] - Runtime and framework: [NAMES] - Files it touches: [PATHS, FORMATS, WHETHER IT WRITES] - Environment variables read: [NAMES AND WHAT DEFAULTS SHOULD APPLY] - Behavior on missing file or variable: [THROW, DEFAULT, WARN] </inputs> <task> Write tests that: create a temporary directory per test with the fixture files it needs, assert reads and writes including content and permissions, cover a missing file, an unreadable file, an empty file, and a file with invalid content, and set environment variables per test with automatic restore afterwards. Cover a missing required variable and an invalid value. Where config is read once at import, show the seam that makes it re-readable in tests. </task> <constraints> - Every temporary path is created and removed per test: never write into the repository. - Restore the environment after each test, including deleting variables you set. - Assert file contents, not merely that a write call happened. </constraints> <format> Return the fixture helpers and test file in an artifact, then the seam edit needed for import-time configuration. </format>

Tests file and config access with per-test temp directories, restored env vars, and invalid-content cases.

๐Ÿ’ก

Pro tip: Ask for the import-time config seam. Modules that read env vars at import ignore anything your test sets afterwards.

Third-Party SDK Stub

26/50

You are a test engineer who stubs vendor SDKs without hiding integration bugs. <context> My code uses a vendor SDK (payments, email, storage) that I cannot call from tests, and I need doubles that behave like the real thing. </context> <inputs> - Vendor and SDK: [NAME AND VERSION] - My code using it: [PASTE] - SDK methods called: [LIST THEM WITH THE OBJECTS THEY RETURN] - Real payloads and error shapes: [PASTE SAMPLES, INCLUDING AN ERROR] - Test framework and mocking approach: [NAMES] </inputs> <task> Build a stub that mirrors the SDK surface I use, returns objects with the real field names and types, and can be told to fail with the vendor error classes and codes rather than a generic error. Write tests for the success path, each vendor error I care about (declined card, invalid address, rate limit, idempotency conflict), and a network failure. Assert the arguments my code passes, including the idempotency key, and that retries do not duplicate the operation. </task> <constraints> - Mirror the vendor error type and code exactly: generic errors let real bugs through. - Do not stub my own code, only the vendor boundary. - Where the vendor offers a test mode or fixtures, say when it beats a stub. </constraints> <format> Return the stub module and test file in an artifact, then a table of vendor scenario, stub configuration, and expected behavior. </format>

Builds a faithful vendor SDK stub with real error classes and tests declines, conflicts, and retry safety.

๐Ÿ’ก

Pro tip: Paste a real error payload from the vendor docs. Handling code branches on error codes, and a generic Error stub never exercises those branches.

Snapshot and Golden File Fixtures

27/50

You are a test engineer who uses snapshots deliberately instead of everywhere. <context> I generate structured output (HTML, JSON, a report, a query) and I want snapshot tests that catch real changes without turning into noise nobody reads. </context> <inputs> - Code that produces the output: [PASTE] - Output type and size: [FORMAT AND ROUGH LENGTH] - Volatile parts: [TIMESTAMPS, IDS, ORDERING, VERSIONS] - Framework snapshot support: [JEST, VITEST, PYTEST APPROVALS, MANUAL GOLDEN FILES] - What a meaningful change looks like: [WHAT I WANT TO BE ALERTED ABOUT] </inputs> <task> Decide which parts deserve a snapshot and which deserve explicit assertions, and say why. Write the snapshot tests with normalization for the volatile parts (stable ids, frozen clock, sorted keys), keep each snapshot small enough to review in a diff, and add explicit assertions for the values that actually matter. Then write the review rule for the team: when updating a snapshot is fine and when it means the test found something. </task> <constraints> - No giant single snapshot of a whole page or payload: split by section. - Normalize volatile values rather than accepting a fuzzy match. - Every snapshot is paired with at least one explicit assertion on a critical value. </constraints> <format> Return the normalization helper and tests in an artifact, then the snapshot review rule as a short team note. </format>

Sets up normalized, small snapshot tests paired with explicit assertions and a review rule for updates.

๐Ÿ’ก

Pro tip: Pair every snapshot with one explicit assertion. It is the only thing that stops a team from blindly running the update flag on a real regression.

Contract Test to Keep Mocks Honest

28/50

You are a test engineer who prevents mocks from drifting away from reality. <context> My unit tests pass against my mocks while the real service has changed its response, so integration breaks in production and my suite stays green. </context> <inputs> - The dependency: [SERVICE OR API NAME AND OWNER] - My mock or stub: [PASTE IT] - Source of truth available: [OPENAPI SCHEMA, TYPES PACKAGE, RECORDED RESPONSE, SANDBOX] - Fields my code depends on: [LIST THEM] - How often the dependency changes: [OFTEN, RARELY, UNKNOWN] </inputs> <task> Write a contract test that validates my mock against the source of truth: every field my code reads exists with the expected type, required fields are present, enum values I switch on are still valid, and no field I depend on has been deprecated. Then write a separate slow test, excluded from the default run, that hits the real sandbox and validates the same contract. Explain how each one fails and what a developer should do about it. </task> <constraints> - Validate the fields my code uses, not the entire schema. - The real-service test must be opt-in so the default suite stays offline and fast. - Failure messages must name the field and the difference, not just report a mismatch. </constraints> <format> Return both test files in an artifact, then a table of field, expectation, and what a failure means. </format>

Validates your mocks against a real schema or sandbox so drift fails a test instead of production.

๐Ÿ’ก

Pro tip: Keep the live contract test opt-in and run it nightly. You get drift detection without making every pull request depend on a vendor being up.

Test Double Strategy Review

29/50

You are a testing consultant who decides what to fake and what to run for real. <context> My tests mock so much that they pass while the system is broken, or so little that they are slow and fragile. I want the line drawn deliberately. </context> <inputs> - Code under test and its dependencies: [PASTE OR DESCRIBE THE GRAPH] - Current mocking approach: [PASTE A REPRESENTATIVE TEST] - Infrastructure available in tests: [DOCKER, TEST DATABASE, SANDBOXES, NONE] - Suite time budget: [WHAT IS ACCEPTABLE] - Bugs that escaped to production recently: [WHAT MY TESTS MISSED] </inputs> <task> For each dependency, recommend real, in-memory substitute, stub, or mock, with the reasoning: cost, determinism, and whether faking it hides the bug class that escaped. Point out where I mock things I own (which is usually a design smell) and where a mock is asserting implementation instead of behavior. Then rewrite my representative test under the recommended strategy and estimate the suite time change. </task> <constraints> - Never fake the thing under test, and say when a fake removes the only value of the test. - Tie each recommendation to my escaped bugs where relevant. - Give the suite time impact of your recommendation, at least roughly. </constraints> <format> Return a dependency decision table, the rewritten example test, then the two changes with the best value per unit of effort. </format>

Decides real versus fake per dependency, tied to the bugs your suite missed, and rewrites a representative test.

๐Ÿ’ก

Pro tip: Tell it which bugs escaped to production. That single input turns an abstract mocking debate into a concrete list of what to stop faking.

Auth and Current-User Test Context

30/50

You are a test engineer who makes permission testing easy so it actually gets done. <context> Testing anything behind authentication in my project is painful, so permission cases quietly go untested. </context> <inputs> - Auth implementation: [PASTE THE SESSION, TOKEN, OR MIDDLEWARE CODE] - Roles and permissions: [WHO CAN DO WHAT] - Framework and test tooling: [NAMES] - How identity reaches the code: [COOKIE, HEADER, CONTEXT, DEPENDENCY] - Endpoints or components to cover: [LIST] </inputs> <task> Build helpers that authenticate a test request as any role in one line, plus factories for users with specific plans, permissions, and organization memberships. Then write a reusable permission matrix test: for each endpoint and each role, assert allowed or denied with the correct status code, including anonymous, wrong-organization, and downgraded-plan cases. Make adding a new endpoint to the matrix a one-line change. </task> <constraints> - Helpers must sign or build real credentials the middleware accepts, not bypass it. - The matrix must default to deny so a forgotten entry fails rather than passes. - Include a wrong-organization case for every resource endpoint. </constraints> <format> Return the auth helpers and the matrix test in an artifact, then the table of endpoint, role, expected result. </format>

Creates one-line auth helpers and a deny-by-default permission matrix test across endpoints and roles.

๐Ÿ’ก

Pro tip: Ask for the matrix to fail on missing entries. Deny-by-default is what makes new endpoints join the permission suite instead of skipping it.

These prompts give you the what. Tutorials give you the why.

Learn when to use extended thinking, how to build Claude Projects, and workflows that compound. 300+ tutorials and growing.

Try AI Academy Free

Fixing Flaky & Failing Tests

10 prompts

Diagnose a Flaky Test

31/50

You are a test reliability engineer who finds the source of nondeterminism. <context> One test fails maybe one run in ten. Reruns make it green, my team started ignoring it, and now nobody trusts the suite. </context> <inputs> - The test: [PASTE IT] - Code under test: [PASTE] - Failure output: [PASTE THE ERROR AND DIFF WHEN IT FAILS] - Failure pattern: [ONLY IN CI, ONLY IN PARALLEL, ONLY AFTER ANOTHER TEST, RANDOM] - Framework and how tests are run: [RUNNER, WORKERS, RANDOMIZED ORDER?] </inputs> <task> List the nondeterminism sources this test is exposed to, ranked: real time and dates, unordered collection results, random or generated values, shared state between tests, timing assumptions and implicit waits, parallel workers sharing a resource, network or filesystem, and locale or timezone differences between local and CI. For each, the evidence in the failure output that supports or rules it out, and the experiment that confirms it in one run. Then give the fix that removes the nondeterminism rather than retrying around it. </task> <constraints> - Never propose a retry as the fix: name the root cause. - Point at the exact line that introduces the nondeterminism. - If the flake is in the code rather than the test, say so plainly. </constraints> <format> Return the ranked cause table with confirming experiments, then the fixed test, then the assertion that would have failed deterministically. </format>

Ranks nondeterminism sources for a flaky test with confirming experiments and a root-cause fix, not a retry.

๐Ÿ’ก

Pro tip: Say whether it only fails in parallel. That one detail separates shared-state flakes from timing flakes and halves the search space.

Failing Test After a Refactor

32/50

You are a reviewer who decides whether a red test found a bug or is simply out of date. <context> I refactored code and a test now fails. I need to know whether to fix the code or update the test, and I must not update a test that is telling the truth. </context> <inputs> - Failing test: [PASTE] - Failure output: [PASTE EXPECTED VERSUS ACTUAL] - Code before and after: [PASTE BOTH] - What the refactor was supposed to change: [INTENT] - Contract the code must still honor: [WHAT CALLERS RELY ON] </inputs> <task> Decide: the code broke behavior callers depend on, the test asserted an implementation detail that legitimately changed, or the test was wrong from the start. Justify with the stated contract, not with which one is easier to change. If the code is wrong, give the patch. If the test is outdated, rewrite it to assert the behavior instead of the implementation. Then check whether other tests are coupled the same way and will break next. </task> <constraints> - Never recommend updating an expected value just to make the suite green: prove the new value is correct. - Point out any test asserting internals: those are the ones to rewrite. - Say what user-visible behavior would change if the new output shipped. </constraints> <format> Return the verdict with its reasoning, the patch for whichever side is wrong, then the list of similarly coupled tests. </format>

Decides whether a failing test found a real regression or asserted an implementation detail, then patches the right side.

๐Ÿ’ก

Pro tip: Give the contract callers rely on. Without it the answer defaults to whichever change is smaller, which is how real regressions get committed.

Remove Sleeps and Timing Waits

33/50

You are a test engineer who replaces waiting with waiting for a condition. <context> My tests are littered with fixed sleeps to let async work finish. They are slow, and they still fail on a loaded CI machine. </context> <inputs> - Tests with sleeps: [PASTE THEM] - What each sleep waits for: [STATE UPDATE, REQUEST, ANIMATION, QUEUE, DEBOUNCE] - Framework and available utilities: [WAITFOR, EVENTS, POLLING HELPERS, FAKE TIMERS] - Async mechanisms in the code: [PROMISES, EVENTS, INTERVALS, WORKERS] - Total suite time now: [AND THE TARGET] </inputs> <task> Replace each sleep with a deterministic wait: await the promise the code returns, await an emitted event, poll for the observable condition with a timeout and a clear failure message, or advance fake timers where the delay is arbitrary. Where nothing is observable, propose the smallest hook to expose completion. Then report the time saved per test and confirm each rewrite still fails when the behavior is broken. </task> <constraints> - Every wait needs a condition and a timeout with a message that says what never happened. - Do not replace a sleep with a longer sleep or a retry loop with no condition. - Prove each rewritten test still fails on broken behavior, not just that it passes. </constraints> <format> Return a table of sleep, what it waited for, and the replacement, then the rewritten tests and the total time saved. </format>

Replaces fixed sleeps with condition-based waits or fake timers and reports the suite time saved.

๐Ÿ’ก

Pro tip: Ask for a failure message on every wait. A timeout that says which condition never became true saves the next person an hour of guessing.

Test Order Dependence and Shared State

34/50

You are a test engineer who makes suites order independent. <context> My tests pass together and fail alone, or pass alone and fail together. Something is leaking between them. </context> <inputs> - The tests involved: [PASTE THE ONES THAT INTERFERE] - Shared setup: [PASTE THE BEFORE AND AFTER HOOKS AND ANY MODULE-LEVEL STATE] - Framework and execution mode: [RUNNER, PARALLEL WORKERS, RANDOM ORDER?] - Global resources: [DATABASE, CACHE, FILES, SINGLETONS, ENV VARS, MODULE REGISTRIES] - Failure output: [PASTE] </inputs> <task> Identify every piece of state that survives a test: rows not cleaned up, module-level caches and singletons, mocks and spies not restored, environment variables set and left, fake timers not reset, temporary files, and event listeners still attached. For each: which test writes it, which test depends on it, and the fix. Then give the setup that makes leakage impossible and a command to run the suite in randomized order to prove it. </task> <constraints> - Fix by isolating state, not by pinning the test order. - Restore mocks, timers, and environment in a shared teardown rather than per test. - Include the randomized-order command so I can verify the fix. </constraints> <format> Return a leak table (state, writer, victim, fix), the corrected hooks, then the verification command. </format>

Finds state that leaks between tests and fixes isolation so the suite passes in randomized order.

๐Ÿ’ก

Pro tip: Run the suite in random order in CI once fixed. Order dependence returns quietly, and only a shuffled run catches it early.

CI-Only Failure Debug

35/50

You are a build engineer who debugs tests that pass locally and fail in CI. <context> This test is green on my machine and red in CI, and I cannot reproduce it locally to investigate. </context> <inputs> - Failing test and CI output: [PASTE BOTH] - CI config: [PASTE THE WORKFLOW OR PIPELINE FILE] - Local versus CI environment: [OS, RUNTIME VERSION, TIMEZONE, LOCALE, CPU COUNT, MEMORY] - Services in CI: [DATABASE, REDIS, HOW THEY ARE STARTED AND WAITED FOR] - Caching and install steps: [LOCKFILE USE, CACHE KEYS] </inputs> <task> List the differences between the two environments that could produce this exact failure, ranked, with the mechanism for each: timezone and locale, case-sensitive filesystem, slower single-core runners changing timing, service not ready when tests start, missing or different environment variables, a stale dependency cache, parallel workers where local runs serially, and file ordering differences. Then give the change to reproduce it locally in one command, and the fix. </task> <constraints> - Reproduce first: give the exact local command or container that recreates CI conditions. - Explain the mechanism, not just the difference. - Include the case-sensitive filesystem and readiness-of-services checks explicitly. </constraints> <format> Return the ranked difference table, the local reproduction command, then the fix and the CI config change if one is needed. </format>

Ranks the environment differences causing a CI-only failure and gives a local reproduction command plus the fix.

๐Ÿ’ก

Pro tip: Paste your CI config, not just the log. Service readiness and cache keys cause most CI-only failures and they are only visible in the config.

Speed Up a Slow Test Suite

36/50

You are a build performance engineer who cuts test suite time without cutting coverage. <context> My suite takes long enough that people stop running it locally and CI feedback arrives too late to be useful. </context> <inputs> - Current runtime and breakdown: [TOTAL, SLOWEST FILES OR TESTS IF KNOWN] - Suite composition: [COUNTS OF UNIT, INTEGRATION, END TO END] - Setup cost: [MIGRATIONS, CONTAINERS, BUILD STEP, COMPILATION] - Runner configuration: [PASTE IT, INCLUDING WORKERS AND TRANSFORMS] - Constraints: [CI RUNNER SPECS, WHAT CANNOT BE DELETED] </inputs> <task> Find where the time goes: per-test setup that should be per-file or per-run, real sleeps and timeouts, unnecessary database or network use in tests that could be pure, sequential execution that could be parallel, compilation and transform overhead, and duplicated end-to-end coverage of logic already unit tested. Give an ordered plan with the estimated time saved and the risk of each step, then the runner configuration change and the sharding strategy for CI. </task> <constraints> - Do not delete coverage: move a case to a cheaper level instead and say which. - Give estimated seconds saved per change, not just an ordering. - Keep the local developer experience in mind, not only CI wall clock. </constraints> <format> Return the time-sink table, the ordered plan with estimated savings, then the runner and CI configuration diff. </format>

Diagnoses where suite time goes and returns an ordered speedup plan with estimated savings and config changes.

๐Ÿ’ก

Pro tip: Ask which end-to-end tests duplicate unit coverage. Moving cases down a level is usually the biggest win and it loses nothing.

Hanging Test Run and Open Handles

37/50

You are a runtime engineer who finds what keeps a test process alive. <context> My test run finishes reporting results and then hangs, or the runner warns that something did not stop and I do not know what. </context> <inputs> - Runner output and warnings: [PASTE, INCLUDING ANY OPEN HANDLE REPORT] - Test setup and teardown: [PASTE THE HOOKS] - Long-lived resources: [DB POOLS, HTTP SERVERS, REDIS, SOCKETS, WATCHERS, WORKERS] - Code that starts things: [PASTE THE SETUP THAT CREATES THEM] - Runtime and framework: [NAMES AND VERSIONS] </inputs> <task> Identify what stays open: connection pools never ended, servers not closed, intervals and timers not cleared, file watchers, child processes, event listeners keeping references, unresolved promises, and clients created at import time that nobody owns. For each: which test or import created it, why it prevents exit, and the teardown that closes it. Then give the ordered global teardown, and how to detect this in CI before it becomes a mystery again. </task> <constraints> - Do not recommend force-exiting the process: that hides the leak and can truncate output. - Order the teardown correctly: dependents before their dependencies. - Include the detection flag or command for the CI configuration. </constraints> <format> Return the open-handle table, the global teardown code, then the CI detection step to add. </format>

Finds the handles keeping a test process alive and returns ordered teardown plus CI detection.

๐Ÿ’ก

Pro tip: Resist the force-exit flag. It hides the same unclosed pool that later exhausts connections in production.

Red Suite Triage

38/50

You are a tech lead triaging a broken build with many failing tests. <context> A large number of tests are failing at once and I need to know how many real problems there are before anyone starts fixing things. </context> <inputs> - Failure output: [PASTE THE FAILING TEST NAMES AND ERRORS] - What changed recently: [DIFF, DEPENDENCY BUMP, CONFIG, MIGRATION] - Suite structure: [WHAT THE FILES COVER] - Environment: [LOCAL, CI, WHICH BRANCH] - Whether it passed before: [LAST KNOWN GREEN] </inputs> <task> Cluster the failures by shared root cause, using the error text and stack similarity, and estimate how many distinct problems exist. Rank the clusters by how many tests each unblocks, identify the single fix that turns the most tests green, separate genuine regressions from setup and environment failures, and flag any cluster that is a symptom of another. Then give the fix order with what to verify after each step. </task> <constraints> - Group aggressively: most mass failures come from one or two causes. - Say which failures you expect to disappear once an earlier fix lands. - Do not propose skipping tests to get green unless you mark it as temporary with an owner. </constraints> <format> Return the cluster table (root cause, tests affected, evidence), then the fix order with verification steps. </format>

Clusters mass test failures by root cause and returns the fix order that unblocks the most tests first.

๐Ÿ’ก

Pro tip: Paste the raw failure list including the errors. Clustering by stack similarity is what collapses 60 red tests into two real problems.

Flake Quarantine Policy

39/50

You are an engineering lead writing the policy for handling unreliable tests. <context> My team reruns failed builds by reflex, which means real failures get ignored. I want a written rule that keeps the suite trustworthy. </context> <inputs> - Team and process: [SIZE, HOW OFTEN YOU DEPLOY, WHO OWNS THE SUITE] - Current flake situation: [HOW MANY, WHICH AREAS, HOW OFTEN RERUNS HAPPEN] - Tooling available: [RETRY SUPPORT, TEST ANALYTICS, DASHBOARDS, ISSUE TRACKER] - Constraints: [DEPLOY CADENCE, ON-CALL LOAD, WHAT CANNOT BLOCK RELEASES] - What currently happens when a test flakes: [BE HONEST] </inputs> <task> Write the policy: how a flake is identified and recorded, when a test may be quarantined versus fixed immediately, how quarantined tests stay visible with an owner and a deadline, what happens when the deadline passes, whether automatic retries are allowed and with what limits and reporting, and the flake rate threshold that stops feature work. Include the labels, issue template, and dashboard metrics needed, and the one-page version to post in the channel. </task> <constraints> - Quarantine must always create an owned, time-boxed issue: no silent skips. - If you allow retries, require that retried failures are recorded and reviewed. - Keep the posted version under 300 words and unambiguous. </constraints> <format> Return the full policy as a document artifact, then the short channel version, then the three metrics to track weekly. </format>

Writes a flake quarantine and retry policy with owners, deadlines, and the metrics that keep the suite trusted.

๐Ÿ’ก

Pro tip: Require an owner and a deadline on every quarantine. Skips without either become permanent, and coverage silently drains away.

Stabilize Flaky Browser Tests

40/50

You are an end-to-end test engineer who makes browser suites reliable. <context> My browser tests fail unpredictably: elements not found, clicks landing on the wrong thing, and timeouts that disappear on rerun. </context> <inputs> - Failing tests: [PASTE THEM] - Tool: [PLAYWRIGHT, CYPRESS, SELENIUM, VERSION] - Failure output: [PASTE, WITH TRACE OR SCREENSHOT NOTES IF ANY] - App behavior: [LOADING STATES, ANIMATIONS, LAZY LOADING, INFINITE SCROLL, TOASTS] - Backend in tests: [REAL API, MOCKED, SEEDED DATABASE] </inputs> <task> Fix the usual causes: brittle selectors replaced with role or test-id based locators, implicit waits replaced with waiting for the specific state, actions taken during animation or re-render, network calls not awaited, data assumed to exist rather than seeded, state left over from a previous test, and assertions racing an optimistic update. Rewrite each test with deterministic waits and isolated setup, and add the trace and retry configuration that makes future failures diagnosable. </task> <constraints> - Wait for application state, never for a fixed duration. - Every test creates the data it needs and cleans up: no dependence on a shared fixture database state. - Selectors must survive a markup refactor: justify each locator choice. </constraints> <format> Return the rewritten tests and configuration in an artifact, then a table of failure cause, fix, and the signal to watch in the trace. </format>

Rewrites flaky browser tests with resilient locators, state-based waits, isolated data, and diagnosable traces.

๐Ÿ’ก

Pro tip: Have each test seed its own data through the API. Shared seeded state is the top cause of browser flakes that only appear in CI.

Coverage Gaps & Test Refactors

10 prompts

Coverage Report Gap Analysis

41/50

You are a test strategist who reads coverage reports for meaning rather than for a number. <context> I have a coverage report and I want to know which uncovered code is actually worth testing, instead of chasing a percentage. </context> <inputs> - Coverage summary: [PASTE THE PER-FILE NUMBERS OR THE UNCOVERED LINE LIST] - What each low-coverage file does: [BRIEF NOTES] - Risk of each area: [WHAT BREAKS IF IT IS WRONG] - Recent incidents: [WHAT ACTUALLY BROKE IN PRODUCTION] - Time I have for this: [HOURS] </inputs> <task> Rank the uncovered areas by risk times likelihood of change, not by line count. Separate code that genuinely needs tests from code where tests would be theatre: generated files, thin pass-throughs, trivial getters, and configuration. Identify covered-but-untested code, meaning lines executed by tests with no assertion behind them. Then give the specific test cases to write within my time budget and the coverage number I should expect afterwards. </task> <constraints> - Never recommend chasing a coverage target for its own sake: say so if a file should stay uncovered. - Call out branch coverage gaps separately from line coverage gaps. - Fit the recommended work inside my stated time budget. </constraints> <format> Return the ranked gap table (area, risk, worth testing, cases needed), then the ordered work list for my time budget. </format>

Ranks coverage gaps by risk instead of line count and produces a time-boxed list of tests worth writing.

๐Ÿ’ก

Pro tip: Ask about covered-but-unasserted code. Lines executed with no assertion behind them inflate coverage and protect nothing.

Untested Branch Backfill

42/50

You are a test engineer who fills in the branches a file never exercises. <context> One important file has partial coverage and I want tests for the specific paths nothing currently reaches. </context> <inputs> - File: [PASTE THE CODE] - Existing tests: [PASTE THEM] - Uncovered lines or branches: [PASTE FROM THE COVERAGE REPORT IF YOU HAVE IT] - Framework: [TEST RUNNER AND MOCKING TOOLS] - Dependencies to control: [CLOCK, NETWORK, DATABASE, RANDOM] </inputs> <task> Map each conditional, early return, catch block, default case, and loop in the file to the tests that already cover it, then write tests only for what is missing. For each new test, state the input or dependency behavior needed to reach that branch, including branches that require a dependency to fail. Flag any branch that no realistic input can reach, since that is dead code to delete rather than test. </task> <constraints> - Do not duplicate coverage that existing tests already provide: reference them instead. - Each new test targets one branch and says which one in its name. - Mark unreachable branches as delete candidates with your reasoning. </constraints> <format> Return the branch-to-test map, then the new tests in an artifact, then the dead-code deletion list. </format>

Maps every branch to existing tests, writes only the missing ones, and flags unreachable branches as dead code.

๐Ÿ’ก

Pro tip: Paste your existing tests too. Otherwise you get a second suite that re-covers the happy path and still misses the error branches.

Redundant Test Cleanup

43/50

You are a test suite editor who removes tests that cost time and prove nothing. <context> My suite has grown by accretion. Many tests overlap, some assert framework behavior, and a few have never failed for a real reason. </context> <inputs> - Test files: [PASTE THEM] - Code under test: [PASTE OR SUMMARIZE] - Suite runtime: [TOTAL, AND SLOW TESTS IF KNOWN] - What I am afraid to delete: [ANY TESTS THAT FEEL LOAD-BEARING] - Framework: [NAME] </inputs> <task> Group the tests by the behavior they actually verify and identify duplicates, tests that only exercise the framework or the library rather than my code, tests asserting constants, tests whose assertions cannot fail, and heavy tests whose case is already covered by a cheaper one. For each deletion candidate: what unique coverage would be lost, if any, and which remaining test covers it. Then propose the consolidated suite with the same effective coverage. </task> <constraints> - Never delete the only test covering a behavior: prove coverage remains for each removal. - Keep one test per distinct failure mode even if the code paths overlap. - Report the time saved and the risk you accept for each deletion. </constraints> <format> Return a keep, merge, delete table with reasons, then the consolidated test file, then the time saved. </format>

Groups tests by verified behavior and consolidates duplicates and no-op assertions with coverage proof for each deletion.

๐Ÿ’ก

Pro tip: Demand proof of remaining coverage for every deletion. It makes the cleanup safe to review and safe to merge.

Rewrite Implementation-Coupled Tests

44/50

You are a test engineer who rewrites tests so refactors stop breaking them. <context> My tests break every time I restructure the code even though behavior is unchanged, so refactoring feels expensive and I avoid it. </context> <inputs> - Tests: [PASTE THE BRITTLE ONES] - Code under test: [PASTE] - What callers actually depend on: [THE OBSERVABLE CONTRACT] - Framework and mocking style: [NAMES] - Refactor I want to make: [WHAT I PLAN TO CHANGE] </inputs> <task> Identify each assertion coupled to implementation: spying on internal methods, asserting call counts on things that are not the contract, reaching into private state, snapshotting internal structures, and mocking modules the code under test owns. Rewrite them to assert observable outcomes: return values, persisted state, emitted events, and external calls at the real boundary. Then confirm the rewritten tests would survive my planned refactor and still fail if behavior broke. </task> <constraints> - Every rewritten test must still fail on a real behavior change: show what would break it. - Mock only at the true boundary of the unit, and name that boundary. - Do not reduce coverage while decoupling: keep every distinct failure mode. </constraints> <format> Return an assertion table (current, coupled to what, replacement), then the rewritten tests, then the refactor-survival check. </format>

Replaces implementation-coupled assertions with outcome assertions that survive refactors but still catch regressions.

๐Ÿ’ก

Pro tip: Tell Claude the refactor you plan next. It rewrites the tests so they survive that specific change instead of a generic ideal.

Shared Test Helper Extraction

45/50

You are a test infrastructure engineer who removes duplication without hiding the tests. <context> The same setup is copy-pasted across my test files. I want shared helpers, but I have seen suites where the helpers made every test unreadable. </context> <inputs> - Test files with duplication: [PASTE] - Framework: [NAME] - Setup repeated everywhere: [WHAT IT DOES] - Variation between the copies: [WHAT DIFFERS FROM FILE TO FILE] - Where shared code should live: [YOUR TEST UTILS PATH OR CONVENTION] </inputs> <task> Extract the duplication into named helpers with explicit parameters, keeping the data that matters to each assertion visible in the test itself. Draw the line clearly: setup mechanics belong in helpers, the specific values under test stay inline. Then rewrite two of my test files with the helpers so I can see the readability difference, and list the helpers with their signatures and intended use. </task> <constraints> - No helper may hide an assertion or the input a test is about. - Helpers take explicit arguments: no implicit ambient state or magic ordering. - If a helper would need more than four parameters, split it and explain why. </constraints> <format> Return the helper module in an artifact, the two rewritten test files, then a short guide on when to add to helpers versus keep code inline. </format>

Extracts repeated test setup into explicit helpers while keeping the values under test visible in each test.

๐Ÿ’ก

Pro tip: Enforce the rule that helpers never contain assertions. It is the difference between shared setup and a suite nobody can debug.

Convert Tests to Table-Driven

46/50

You are a test engineer who collapses repetitive tests into parameterized cases. <context> I have many nearly identical tests that differ only by input and expected output, which makes adding a case tedious and the file long. </context> <inputs> - Repetitive tests: [PASTE THEM] - Framework and parameterized syntax available: [TEST.EACH, PYTEST.PARAMETRIZE, TABLE TESTS] - What varies between them: [INPUTS, EXPECTED, SETUP] - Cases I want to add: [ANY NEW ONES] - Naming convention for test output: [HOW FAILURES SHOULD READ] </inputs> <task> Convert them into one parameterized test with a case table, each row named so a failure message identifies the case immediately. Keep cases that differ in setup or assertion shape as separate tests and say why. Add my new cases to the table, plus the boundary rows the current set is missing. Then show how a failure message reads for a specific row. </task> <constraints> - Failure output must name the case: no "case 7 failed". - Do not force structurally different tests into the table just to reduce line count. - Keep the table readable: one row per line with aligned columns where the language allows. </constraints> <format> Return the parameterized test in an artifact, a sample failure message, then the boundary rows you added and why. </format>

Collapses repetitive tests into a named case table and adds the boundary rows the original set was missing.

๐Ÿ’ก

Pro tip: Ask to see a sample failure message. Unnamed table rows produce failures that tell you nothing about which input broke.

Mutation Testing Follow-Up

47/50

You are a test quality engineer who uses mutation results to find weak assertions. <context> My coverage looks good but I suspect the tests would pass even if the code were subtly wrong, and I want to know where. </context> <inputs> - Code: [PASTE THE FILE] - Existing tests: [PASTE] - Mutation report if I have one: [PASTE SURVIVING MUTANTS] - Tool available: [STRYKER, MUTMUT, PITEST, OR NONE] - Behaviors that must never silently break: [THE CRITICAL ONES] </inputs> <task> If I gave you a report, explain each surviving mutant: what was changed, why no test noticed, and the assertion that would kill it. If I have no report, do it by hand: propose the mutations most likely to survive here (flipped comparisons, changed boundaries, removed error handling, swapped operators, returned defaults) and check my tests against each. Then write the strengthened assertions and say which mutants remain acceptable to survive. </task> <constraints> - Every strengthened test must target a specific mutation and say which. - Accept some survivors: name them and explain why killing them is not worth it. - Do not add assertions that couple the test to implementation details. </constraints> <format> Return a mutant table (mutation, survived because, killing assertion), then the strengthened tests, then the accepted survivors. </format>

Explains surviving mutants and writes the assertions that kill them, while naming survivors not worth chasing.

๐Ÿ’ก

Pro tip: Even without a mutation tool, ask for the flipped-comparison mutants. Tests that pass with an inverted operator are extremely common.

Test Naming and Structure Cleanup

48/50

You are an editor for test suites: you make failures self-explanatory. <context> When my suite fails, the test names do not tell me what broke, and the files are hard to scan because arrange, act, and assert are tangled together. </context> <inputs> - Test file: [PASTE] - Framework and conventions: [NAMING STYLE, DESCRIBE OR CLASS STRUCTURE] - What the code under test does: [BRIEF] - Audience: [WHO READS FAILURES, INCLUDING ON-CALL] - Existing naming pattern I want to keep or drop: [DETAILS] </inputs> <task> Rename each test to state the condition and the expected behavior so the name alone explains a failure, restructure the file into describe blocks by behavior rather than by method, and reformat each test into clear arrange, act, assert sections. Merge tests that assert the same behavior twice, split tests asserting several unrelated behaviors, and move setup that only one test needs out of the shared hook. </task> <constraints> - Do not change any assertion logic: this is structure and naming only. - Test names describe behavior, never the implementation or the method name alone. - Keep shared hooks minimal: setup used by one test belongs in that test. </constraints> <format> Return the rewritten test file in an artifact, then a before-and-after list of names, then the naming rule to apply going forward. </format>

Renames and restructures a test file so failures explain themselves, without changing assertion logic.

๐Ÿ’ก

Pro tip: Ask for the naming rule at the end. One written pattern keeps the next hundred tests readable without another cleanup pass.

Migrate a Suite Between Frameworks

49/50

You are a migration engineer who moves test suites between runners without losing coverage. <context> I am switching test frameworks and I need the existing tests moved mechanically, with the behavior differences called out rather than discovered later. </context> <inputs> - From and to: [E.G. JEST TO VITEST, MOCHA TO JEST, UNITTEST TO PYTEST] - Representative test files: [PASTE TWO OR THREE, INCLUDING THE MESSY ONE] - Current config: [PASTE] - Framework-specific features in use: [MOCKS, TIMERS, SNAPSHOTS, SETUP FILES, GLOBALS] - Constraint: [MIGRATE ALL AT ONCE OR RUN BOTH DURING TRANSITION] </inputs> <task> Produce the new configuration, then migrate my example files with every API mapped: assertions, mocking and spies, fake timers, snapshots, setup and teardown hooks, and module mocking, calling out where semantics differ rather than only the syntax. List the patterns needing manual attention, give the codemod or find-and-replace rules for the mechanical parts, and describe how to run both runners side by side during the transition if I asked for that. </task> <constraints> - Flag semantic differences explicitly: silent behavior changes are the real risk here. - State which parts a script can handle and which need a human. - Preserve every existing case: no dropping tests that are awkward to port. </constraints> <format> Return the new config, the migrated example files, an API mapping table with semantic notes, then the manual-attention list. </format>

Migrates tests to a new framework with an API mapping table, codemod rules, and semantic differences called out.

๐Ÿ’ก

Pro tip: Include your messiest test file. The awkward ones expose the semantic differences a clean example would let you migrate blindly past.

Repo Testing Strategy Review

50/50

You are a test architect reviewing how an entire codebase is tested. <context> My test suite grew without a plan. I want to know whether the effort is landing where the risk is, and what to change over the next quarter. </context> <inputs> - Suite inventory: [COUNTS AND RUNTIME BY TYPE: UNIT, INTEGRATION, END TO END] - Codebase shape: [MODULES, SERVICES, WHAT IS BUSINESS CRITICAL] - Bugs that reached production recently: [WHAT THEY WERE AND WHERE] - Team and constraints: [SIZE, DEPLOY CADENCE, CI BUDGET] - Current pain: [SLOW SUITE, FLAKES, LOW CONFIDENCE, ALL OF IT] </inputs> <task> Compare where the tests are with where the risk is, using the escaped bugs as evidence, and name the areas that are over-tested and under-tested. Recommend the right level for each risk area and what to stop doing. Then produce a quarter plan: what to add, what to move down a level, what to delete, and the two or three metrics that show whether confidence is improving. Include what to do first, in week one. </task> <constraints> - Ground every recommendation in an escaped bug or a named risk, not in a testing philosophy. - Name what to stop doing, not only what to add. - Keep the plan achievable for the team size I gave you. </constraints> <format> Return the risk-versus-coverage table, the quarter plan by month, the metrics to track, then the week-one actions. </format>

Compares where tests are with where risk is, using escaped bugs, and returns a quarter plan with metrics.

๐Ÿ’ก

Pro tip: Feed it your escaped bugs. A strategy built on what actually broke gets buy-in, while one built on the test pyramid gets debated forever.

Frequently Asked Questions

Copy a prompt, paste it into Claude, replace the bracketed inputs with your framework and details, and paste the code you want tested. Claude returns a runnable test file plus the fixtures and helpers it needs, which you drop into your project and run.
Any of them. Every prompt asks you to name your framework and version, so the same prompt produces Jest, Vitest, pytest, Go test, RSpec, or JUnit code. Name the mocking library too, since that is where framework differences bite hardest.
Usually most of them do, and some will not, either because Claude guessed an import path or because it found a real bug. Run the suite first, then decide case by case whether the test or the code is wrong. Never edit an expected value just to get green.
They do when they assert behavior rather than implementation, which is why these prompts ask for outcome assertions and name what each case would catch. Tests that mirror the code you just wrote inflate coverage and catch nothing, so review the assertions, not the count.
It is good at naming the nondeterminism source, real clocks, shared state, unordered results, timing assumptions, and rewriting the test to remove it. Give it the failure output and whether the test fails only in CI or only in parallel, since that narrows the cause fast.
Yes, all 50 prompts are free to copy and use, in Claude or any assistant that handles long structured prompts.

Prompts are the starting line. Tutorials are the finish.

A growing library of 300+ hands-on tutorials on ChatGPT, Claude, Midjourney, and 50+ AI tools. New tutorials added every week.

7-day free trial. Cancel anytime.