Back to cookbook

Prompt to Generate Unit Tests From a Function

17 views Published

Make this prompt yours

Share

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

Make this prompt yours

prompt-template
134 tokens
You are a senior software engineer writing unit tests. Function to test: [PASTE THE FUNCTION CODE] Language and test framework: [E.G. TYPESCRIPT WITH VITEST, PYTHON WITH PYTEST] Instructions: 1. Write tests covering normal, expected inputs. 2. Write tests covering edge cases: empty input, null/undefined, boundary values. 3. Write tests covering any error conditions the function should raise or handle. 4. Use clear, descriptive test names that state what is being verified. 5. Return only the test code, in a single code block, ready to run. Output format: one fenced code block containing the complete test file.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
44 tokens
Function to test: function divide(a, b) { if (b === 0) throw new Error("Cannot divide by zero"); return a / b; } Language and test framework: JavaScript with Jest

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.

Found this prompt useful? Share it.

Share

More in Code Generation & Software Engineering

Code Generation & Software Engineering

ChatGPT Prompt to Generate a Production-Ready Dockerfile for Your App

This Dockerfile generator prompt gives ChatGPT, Claude, or Gemini everything needed to write a secure, production ready Dockerfile for your…

You are an expert DevOps engineer who writes secure, production-ready Dockerfiles.

Context:
- Application language and version: [LANGUAGE AND VERSION, e.g., Node.js 20]
- Framework: [FRAMEWORK, e.g., Express, Django, Spring Boot]
- Package manager: [PACKAGE MANAGER, e.g., npm, pip, Maven]
- Target deployment platform: [PLATFORM, e.g., AWS ECS, Kubernetes, linux/amd64]
- Special requirements: [e.g., private package registry, native dependencies, health checks]

Task:
Write a production-ready Dockerfile for this application. Use a multi-stage build that separates the build/dependency-install stage from the final runtime stage. The final image should:
1. Use the smallest reasonable base image for the runtime.
2. Run as a non-root user.
3. Only copy the files needed to run the application, not build tools or source maps.
4. Include a HEALTHCHECK instruction appropriate for this type of service.
5. Set any necessary environment variables and expose the correct port.

Constraints:
- Do not use the "latest" tag for any base image; pin a specific version.
- Keep the final image size as small as possible.
- Explain, in a short comment above each non-obvious instruction, why it's there.

Output format:
1. The complete Dockerfile in a single code block.
2. A short bullet list explaining the base image choice and any trade-offs.
3. One suggested .dockerignore entry list for this stack.

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Debug a Failing API Test Using Postman's MCP Server

This prompt helps developers and QA engineers debug a failing API test by having an AI assistant like Claude or ChatGPT pull live request an…

ROLE: You are a senior API test engineer helping debug a failing test in a Postman collection accessed through an MCP connection.

CONTEXT:
- Collection name: [COLLECTION_NAME]
- Failing request/folder: [REQUEST_OR_FOLDER_NAME]
- Environment: [ENVIRONMENT_NAME]
- Last known good run (if available): [RUN_ID_OR_DATE]

TASK:
1. Retrieve the failing request's details (method, URL, headers, body) and its actual response (status code, headers, body) from the connected Postman MCP server.
2. Identify the exact assertion or test script line that failed, quoting it directly.
3. Compare the failing response against the expected response or the last known good run, and list every meaningful difference.
4. Classify the likely root cause as one of: schema change, authentication/authorization failure, timeout/network issue, environment misconfiguration, or application bug.
5. Propose a specific fix or next diagnostic step for that category.

CONSTRAINTS:
- Do not guess at response data you have not actually retrieved; if the MCP call fails, say so explicitly.
- Keep the explanation under 200 words before listing the fix.

OUTPUT FORMAT:
- Summary: [one-sentence description of the failure]
- Evidence: [key request/response fields and the failing assertion]
- Root cause category: [one of the five categories above]
- Recommended fix: [specific, actionable step]

Make this prompt yours

Code Generation & Software Engineering

AI Prompt to Generate an OpenAPI Spec From Existing API Code

This OpenAPI spec generator prompt tells ChatGPT, Claude, or Gemini how to read your existing API route handlers, controllers, or endpoint f…

ROLE
You are an API documentation specialist who writes precise OpenAPI 3.x specifications strictly from the code provided.

CONTEXT
Language/framework: [LANGUAGE_AND_FRAMEWORK]
Source code for this route group:
[PASTE_ROUTE_OR_CONTROLLER_CODE]
Existing spec file to extend, if any: [EXISTING_OPENAPI_FILE_OR_NONE]

TASK
For each endpoint in the provided code:
1. Identify the HTTP method, path, and path/query parameters with their types
2. Infer the request body schema from validation logic, type annotations, or serializers
3. Infer every possible response, including success and all error status codes the handler can return
4. Mark any field you cannot determine with confidence as [NEEDS REVIEW] in a comment rather than guessing

CONSTRAINTS
- Do not invent fields, parameters, or response codes that are not implied by the code
- Use OpenAPI 3.1 syntax unless [OPENAPI_VERSION] specifies otherwise
- Reuse and reference shared schemas with $ref instead of duplicating object definitions
- Keep descriptions factual and based only on what the code does, not assumed business intent

OUTPUT FORMAT
Return a single valid YAML OpenAPI document, followed by a short bullet list titled 'Needs Human Review' for anything flagged uncertain.

Make this prompt yours