Prompt to Generate Unit Tests From a Function
This prompt turns an existing function into a set of unit tests covering its normal behavior, edge cases, and error handling, built for developers who write code faster than they write tests and want a solid first draft to review.
Instead of a vague request to "write some tests," it tells the model exactly which framework to target and which categories of cases to cover, so the output is a test file you can drop into your project rather than a handful of scattered examples.
Prompt template
Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.
Example input
When to use it
- Adding test coverage to an existing function that currently has none
- Generating a first draft of edge cases you might not think of yourself
- Standardizing test structure and naming across a team
- Quickly checking whether a refactor changed a function's behavior
Best practices
- Paste the actual function code, not a description of what it does
- Name the testing framework and language version explicitly
- Ask for edge cases like empty input, nulls, and boundary values separately
- Run the generated tests yourself before committing; treat them as a draft
Common mistakes
- Not specifying the test framework, getting output in the wrong syntax
- Skipping the edge-case request and only getting happy-path tests
- Committing generated tests without running them first
- Testing implementation details instead of the function's actual behavior
FAQs
Will the generated tests actually pass?
Usually, if the function works as described, but always run them yourself first. Treat the output as a strong first draft, not a merge-ready commit.
How do I get it to cover more edge cases?
List specific scenarios you're worried about, like very large numbers or concurrent calls, directly in the prompt instead of relying on the model to guess them.
Does this work for untyped languages like plain JavaScript?
Yes, just name the framework such as Jest or Mocha instead of a typed one; the structure of the prompt doesn't change.
Can I use this for integration tests instead of unit tests?
Not directly. This template is scoped to a single function in isolation. For integration tests, describe the components involved and the flow between them instead.