The fastest way to get tests out of Cursor: switch to Agent mode, hand it the code with an @Files reference, and tell it to write the tests and run them. Agent writes the tests, runs your test command in the terminal, reads the pass/fail output, and edits tests or code in a loop until everything is green — you review the finished diff instead of babysitting each step.

Each prompt below names the framework, points at exact paths with @-symbols, and tells Agent to name tests by behavior and cover the edges. New to prompting Cursor well? Start with the best Cursor prompts roundup, and pair these with debugging prompts and refactoring prompts for the full loop.

Advertisement

Unit tests

Four prompts for solid unit coverage. Name the framework, point at the file, and tell Agent to run the suite so the tests actually execute.

1. Thorough Unit Tests, Then Run Them

Agent mode. Write thorough unit tests for @File [path/to/module.ts].

Framework: [Jest / Vitest / pytest / Go testing]. Put the tests in [path/to/module.test.ts] next to the existing tests, matching their style.

Do this:
- Cover the happy path, edge cases, and error paths for each exported function.
- Name each test after the behavior it verifies, not the function name.
- Don't touch the source or any unrelated files.
- Then run [npm test / pytest -q / go test ./...] and fix any failures until the whole suite is green.
Show me the final diff and the passing test output.

Why it works: Naming the framework, the file, and the run command lets Agent close the loop itself instead of handing you tests that were never executed.

2. Boundary and Edge-Case Tests

Add the boundary and edge-case tests I'd forget for @File [path/to/module].

Framework: [Vitest / pytest]. Add to [existing test file].

Cover these explicitly:
- Empty, null/None, and single-element inputs.
- Minimum, maximum, zero, and negative values.
- Off-by-one boundaries and just-past-the-limit cases.
- Unicode, very long strings, and whitespace-only input where relevant.
Name each test after the exact condition it checks. Run the suite and fix failures. Don't change the source unless a test reveals a real bug — if it does, stop and tell me first.

Best for: The cases real bugs hide in — spelling out the boundaries stops Agent settling for happy-path assertions.

3. Error-Path and Exception Tests

Write tests for the failure behavior of @File [path/to/module], not just the success path.

Framework: [Jest / pytest / Go testing].

Do this:
- Assert the exact error type/message thrown for each invalid input.
- Cover thrown exceptions, rejected promises, and returned error values as the code uses them.
- Test that cleanup still runs on failure (files closed, transactions rolled back).
- Verify no partial state is left behind after an error.
Run the tests and fix failures until green. Report any error path that the code doesn't actually handle.

Why it works: Error handling is the least-tested code and the most likely to break in production; targeting it directly surfaces gaps a happy-path suite never touches.

4. Table-Driven / Parametrized Tests

Rewrite the repetitive tests for @File [path/to/module] as one table-driven / parametrized test.

Framework: [Go testing t.Run / pytest.mark.parametrize / Vitest test.each].

Do this:
- Build a table of cases: input, expected output, and a descriptive name per row.
- Include the edge and error rows, not only typical values.
- Keep each case independent so one failure doesn't hide the others.
- Make failure messages show which row failed and why.
Run the suite and confirm all rows pass. Keep behavior coverage identical or better than the tests you replace.

Best for: Turning copy-pasted test blocks into one readable table where adding a new case is a single line.

Coverage gaps

Four prompts that find what you are not testing. Give Agent the code and the existing tests so it does gap analysis instead of duplicating what you have.

5. Find Untested Paths

Ask mode. Here's my code and my current tests: @File [path/to/module] and @File [path/to/module.test].

Tell me what I'm not testing:
- List the untested branches, paths, and edge cases, ranked by risk.
- For each, say what could break in production if it stays untested.
- Flag any branch that looks untested because it's actually unreachable or dead code.
Don't write tests yet — just give me the ranked gap list so I can decide what's worth covering.

Why it works: Handing Agent both the code and the existing tests turns coverage into a gap analysis; Ask mode keeps it read-only so you plan before anything gets written.

6. Tests for the Riskiest Branches First

Agent mode. Using the gap list for @File [path/to/module], write tests for the highest-risk branches first.

Framework: [Jest / Vitest / pytest].

Do this:
- Start with the branches around money, auth, permissions, and data loss.
- One behavior per test, named after the condition it exercises.
- Don't write tests that only assert a mock was called — assert real outcomes.
- Skip getters/setters and trivial glue.
Run the suite after each group and fix failures. Stop when the risky branches are covered and tell me what's left.

Best for: Spending test effort where a bug would actually hurt, instead of padding a coverage number on trivial code.

7. Tests for a Recently Changed File

Agent mode. Look at @Git for my recent changes and write tests for what changed in [path/to/file].

Framework: [Vitest / pytest].

Do this:
- Focus on the new and modified behavior in the diff, not the whole file.
- Add a regression test for any bug the change was meant to fix.
- Cover the new edge cases the change introduces.
- Match the existing test file's style and location.
Run the suite and fix failures until green. Summarize which lines of the diff are now covered and which aren't.

Why it works: @Git scopes Agent to the diff, so you get tests for the code you just touched rather than a rewrite of the entire suite.

8. Raise Coverage to a Target

Agent mode. Raise test coverage for @Folder [src/module] to [85]% line and branch coverage.

Framework: [Jest --coverage / pytest --cov / go test -cover].

Do this:
- Run coverage first and show me the current numbers and the least-covered files.
- Add meaningful tests for the uncovered branches — real assertions, no tests that pass without checking anything.
- Re-run coverage after each file and report progress.
- Don't game the metric: no empty tests, no asserting on mocks, no deleting hard-to-test code.
Stop at the target and give me the before/after coverage report.

Best for: Hitting a CI threshold honestly — the anti-gaming rules keep Agent from writing tests that lift the number without catching anything.

Advertisement

Integration & E2E

Four prompts for tests that cross boundaries — routes, databases, browsers, and external APIs. Tell Agent what's real and what's mocked, and have it run the tests against a real environment.

9. Integration Test for an API Route

Agent mode. Write an integration test for the API route in @File [path/to/route].

Framework: [Jest + supertest / pytest + httpx / Go net/http/httptest]. Put it in [tests/integration/].

Do this:
- Exercise the real route end to end: request in, response out, through the handler.
- Test success, validation errors (400), auth failures (401/403), and not-found (404).
- Assert status code, response body shape, and any side effects (row written, event emitted).
- Mock only external third-party calls; keep the app's own layers real.
Run the integration suite and fix failures until green.

Why it works: Keeping the app's own layers real while mocking only third parties tests the wiring, which is exactly where unit tests miss bugs.

10. Database Integration Test With Fixtures

Agent mode. Write a database integration test for the queries in @File [path/to/repo-layer].

Framework: [pytest + a test Postgres / Jest + Testcontainers / Go + sqlmock or a real test DB].

Do this:
- Spin up an isolated test database (Testcontainers or a dedicated test schema), not the dev DB.
- Load fixtures before each test and roll back or truncate after, so tests don't leak state.
- Test real queries against real data: filters, joins, ordering, and edge cases (empty results, nulls, duplicates).
- Assert on the returned rows, not on the SQL string.
Run the tests and fix failures. Make sure they're repeatable — run them twice and confirm identical results.

Best for: Catching query bugs a mocked DB hides — running against a real database with fixtures tests the SQL, not a stub.

11. Playwright / Cypress E2E for a User Flow

Agent mode. Write an end-to-end test for the [signup and first login] flow.

Framework: [Playwright / Cypress]. Put it in [e2e/]. App runs at [http://localhost:3000].

Do this:
- Drive the real UI: fill the form, submit, follow redirects, assert the user lands on [dashboard].
- Select elements by role or test-id, not brittle CSS or text that changes.
- Cover the unhappy path too: invalid input shows the right error and no redirect.
- Wait on real conditions (visible element, network idle), never fixed sleeps.
Run the E2E suite headless and fix failures. Keep each test independent — no shared login state between specs.

Why it works: Role/test-id selectors and condition-based waits are the two things that separate a stable E2E suite from a flaky one; asking for them up front avoids a rewrite later.

12. Contract Test for an External API

Agent mode. Write a contract test for our integration with the [Stripe / third-party] API in @File [path/to/client].

Framework: [Jest / pytest]. Put it in [tests/contract/].

Do this:
- Assert the request we send matches the shape the API expects (method, path, headers, body fields).
- Assert we correctly parse a real sample response, including error responses.
- Mock the transport for the fast suite, but add one live test (skipped in CI, run on a schedule) that hits the real sandbox so we notice if their API changes.
- Fail loudly if a required field is missing on either side.
Run the mocked suite and fix failures. Explain how to run the live contract check.

Best for: Noticing when a vendor changes their API before your users do — the scheduled live check keeps your mocks honest.

Test data & mocks

Four prompts for the scaffolding around tests. Realistic data and correct mocks are what make the rest deterministic.

13. Realistic Fixtures and Factories

Agent mode. Create test factories/fixtures for the models in @File [path/to/models].

Framework/tool: [factory_boy / Fishery / Faker / a plain builder]. Put them in [tests/factories/].

Do this:
- One factory per model with sensible realistic defaults and easy per-test overrides.
- Include traits/variants for common states (e.g. admin user, expired subscription, empty cart).
- Generate valid related records so foreign keys and required fields are satisfied.
- Add a couple of deliberately invalid variants for negative tests, clearly labeled.
Then refactor two existing tests to use the factories and run them to prove they still pass.

Why it works: Factories with overrides beat hand-built objects in every test — one place to change when the model does, and traits make the intent of each test obvious.

14. Mock an External Service or API

Agent mode. Mock the [payment / email / third-party API] calls in the tests for @File [path/to/client].

Framework/tool: [msw / nock / responses / pytest monkeypatch].

Do this:
- Intercept at the network boundary so our code runs unchanged — don't rewrite the client to accept a mock.
- Provide realistic success responses and at least one failure response (timeout, 500, 429) per endpoint used.
- Assert our code handles each response correctly, including retries and error surfacing.
- Keep the app's own logic real; only the external call is stubbed.
Run the suite and fix failures until green.

Best for: Fast, offline tests that still exercise your real code path — mocking at the network layer avoids polluting the app with test-only branches.

15. Mock Time, Network, and Randomness

Agent mode. Make the tests for @File [path/to/module] deterministic by controlling time, randomness, and network.

Framework: [Vitest fake timers / Jest / pytest freezegun / Go clock injection].

Do this:
- Freeze or inject the clock so date/time-dependent behavior is stable and testable across timezones.
- Seed or stub randomness (UUIDs, random IDs, shuffles) so results are reproducible.
- Ensure no test touches the real network — fail if it tries.
- Add explicit tests for tricky moments: DST change, month/year boundary, expiry exactly at the deadline.
Run the suite twice and confirm identical results both times.

Why it works: Time, randomness, and network are the three sources of flakiness; pinning all three and running twice proves the suite is actually deterministic.

16. Seed a Test Database

Agent mode. Write a seed/setup routine for the test database used by @Folder [tests/].

Stack: [Prisma / SQLAlchemy / Drizzle / raw SQL], test DB: [Postgres / SQLite].

Do this:
- Create a reusable setup that migrates a fresh schema and inserts a known baseline dataset.
- Make it idempotent and fast: reset between test files without leaking data.
- Cover the key entities and a few edge records (empty relations, soft-deleted rows).
- Wire it into the test lifecycle (global setup + per-test transaction rollback where possible).
Run the full suite to confirm seeding works and tests stay isolated.

Best for: A clean, known starting state for every DB test — idempotent seeding plus rollback keeps tests independent and fast.

Fix & maintain tests

Three prompts for the tests you already have. Let Agent reproduce the problem, then verify the fix.

17. Fix a Flaky Test

Agent mode. This test is flaky — it passes sometimes and fails others: @File [path/to/flaky.test].

Do this:
- Run it several times (or with --repeat) to observe the intermittent failure.
- Diagnose the cause: timing/async, test ordering, shared state, randomness, time/timezone, or real network.
- Fix the root cause — make it deterministic — instead of adding a sleep or a retry that just hides it.
- If it's an ordering/shared-state issue, isolate the test properly.
Re-run it 20 times and confirm it passes every time. Explain what was flaky and why the fix is stable.

Why it works: Making Agent reproduce the flake and then re-run 20 times proves the fix, rather than papering over it with a sleep that returns next week.

18. Refactor Slow or Brittle Tests

Agent mode. The tests in @File [path/to/slow.test] are slow and brittle. Refactor them without losing coverage.

Do this:
- Show me the slowest tests first (timing), then the most brittle (over-mocked, coupled to implementation).
- Replace implementation-coupled assertions with behavior assertions.
- Cut needless setup, share fixtures, and swap real I/O for the right mock where safe.
- Keep the same behavior coverage — don't delete a test just because it's slow; speed it up.
Run the suite before and after, and report the coverage and runtime for each.

Best for: A test suite that's become a chore to run — measuring before and after keeps the refactor honest about coverage.

19. Migrate a Test Framework

Agent mode. Migrate the tests in @Folder [tests/] from [Mocha/Chai] to [Vitest] (or [unittest] to [pytest]).

Do this:
- Plan the migration and list the API mappings (assertions, hooks, mocks, config) before editing.
- Convert file by file, preserving every assertion and case — don't drop coverage.
- Update config and scripts (test command, coverage, CI) to the new runner.
- Flag anything that doesn't map cleanly and ask before guessing.
After each batch, run the migrated tests and fix failures until the whole suite passes on the new framework.

Why it works: Asking Agent to plan the API mappings and migrate in batches keeps a framework swap reviewable and stops it silently dropping cases.

TDD with Agent

Three prompts that lean into Agent's loop: write the test, watch it fail, make it pass. Cursor iterates on the test output on its own.

20. Write Failing Tests From a Spec, Then Implement

Agent mode, TDD. Here is the spec for [feature]:

[paste the spec: inputs, outputs, rules, edge cases]

Framework: [Vitest / pytest].

Do this:
- First write the tests that capture this spec, including edge and error cases. Run them and confirm they FAIL for the right reason (red).
- Then implement the code in [path/to/module] to make them pass (green) — smallest change that satisfies the tests.
- Don't weaken or delete a test to force a pass; if the spec is ambiguous, ask.
Re-run until all tests pass, then show me the red-to-green sequence and the final diff.

Why it works: Confirming the tests fail first proves they're actually testing the new behavior, so green means the feature works — not that the tests were empty.

21. Agent Writes Tests and Code, Iterates Until Green

Agent mode. Build [feature/function] end to end and don't stop until it's proven working.

Requirement: [what it must do]. Acceptance: [how we'll know it's done].
Framework: [Jest / pytest]. Test command: [npm test / pytest -q].

Do this:
- Outline a plan, then write tests for the acceptance criteria and the edge cases.
- Implement the code to satisfy them.
- Run the tests, read the output, fix failures, and repeat the run/fix loop until everything passes.
- Don't touch unrelated files, and don't lower the bar in the tests to make them pass.
When it's green, summarize what you built, what's covered, and anything still risky.

Best for: Letting Agent own the whole red-green loop — clear acceptance criteria give it a finish line it can verify against.

22. Characterization Tests Before a Refactor

Agent mode. I'm about to refactor @File [path/to/legacy] but it has no tests. Make it safe first.

Framework: [Jest / pytest / Go testing].

Do this:
- Read the code and pin down what it actually does right now — bugs and quirks included.
- Write characterization tests that lock in that current behavior, so any change that alters it will fail.
- Run them and confirm they pass against the code as-is.
- Don't fix any bugs yet — just capture today's behavior.
Once they're green, tell me the safest order to do the refactor: [describe the refactor].

Why it works: Characterization tests snapshot existing behavior before you touch it, so a refactor can't silently change something you didn't mean to.

Save your testing conventions — framework, file locations, the "run the tests and fix failures" rule, no-trivial-tests policy — in a .cursor/rules file so Cursor applies them in every session. For the wider workflow, keep the best Cursor prompts handy and reach for the debugging prompts when a test surfaces a real bug.

Frequently Asked Questions

Can Cursor run the tests it writes?

Yes. In Agent mode, Cursor runs your test command in the integrated terminal, reads the pass/fail output, and edits either the tests or the code until they pass. Tell it the exact command (for example npm test or pytest -q) and say "run the tests and fix failures until green." With auto-run enabled it won't stop to confirm each command; without it, you approve each terminal run. Ask mode won't run anything — it only reads and answers.

Which test framework does Cursor use?

Whichever your project already uses — Cursor detects it from your package.json, config files, and existing tests. To be safe, name it in the prompt: Jest, Vitest, pytest, Go's testing package, JUnit, RSpec, or Playwright/Cypress for E2E. If you don't specify and the repo is ambiguous, Cursor may pick a different runner than your CI, so state the framework and the file location for new tests.

How do I get real coverage instead of fake or trivial tests?

Point Cursor at behavior, not lines. Give it the code plus the existing tests with @Files, ask it to list untested branches and edge cases ranked by risk, and only then write tests for those gaps. Ban assertions that just restate the implementation, require boundary and error-path cases, and tell it to run the tests so they actually execute. Chasing a coverage percentage alone produces tests that pass without checking anything meaningful.

How do I mock external services in Cursor tests?

Tell Cursor which boundary to mock and which to keep real. Point it at the client module with @Files and ask it to stub the network layer (msw, nock, responses, or the framework's built-in mocks) so tests don't hit the live API. Have it mock time, randomness, and network for determinism, and add one contract test that runs against the real API on a schedule so your mocks don't drift from reality.

Can I do test-driven development in Cursor?

Yes, and Agent mode fits TDD well. Ask it to write failing tests from a spec first, run them to confirm they fail (red), then implement the code and re-run until they pass (green), without weakening the tests to force a pass. Cursor loops on the test output on its own, so you review the finished red-green cycle and the diff rather than driving each step by hand.

How do I stop Cursor writing trivial or duplicate tests?

Give it the existing tests as context so it does gap analysis instead of regenerating what you have, and add explicit constraints: no tests that only assert a mock was called, no duplicates of existing cases, one behavior per test named after that behavior. Ask it to skip getters/setters and framework glue and focus on logic, branches, and edge cases. A .cursor/rules file with your testing conventions keeps this consistent across every session.

Advertisement