How to Generate Unit Tests for a Function with Claude Code
Point Claude Code at a single function and get a focused, runnable test file in your project's existing test framework.
Writing the first batch of tests for an untested function is the slowest part of testing. Claude Code can read the function, infer its contract, and write a test file that matches the framework and conventions already in your repo. The trick is to scope the request tightly so you get a small, real test file instead of a sprawling, fragile one.
What you need
- Claude Code installed and authenticated in your terminal
- A project that already has a test runner (Jest, Vitest, pytest, or similar)
- One specific function you want covered
Step 1: Open Claude Code in the project root
Run the CLI from the top of your repository so Claude can see your config files, existing tests, and package manifest. That context is how it picks the right framework and assertion style without you spelling it out.
Step 2: Ask for tests on one function only
Name the file and the function. Tell Claude to match the framework already in use and to put the test where your other tests live. A narrow prompt keeps the output reviewable.
Step 3: Review the generated test cases
Read each case before accepting. Confirm the assertions describe behavior you actually want, not just behavior the current code happens to produce. If Claude invented a case that does not apply, ask it to drop that one.
import { describe, it, expect } from "vitest";
import { parseDuration } from "../time";
describe("parseDuration", () => {
it("parses minutes and seconds", () => {
expect(parseDuration("2m30s")).toBe(150);
});
it("returns 0 for an empty string", () => {
expect(parseDuration("")).toBe(0);
});
it("throws on malformed input", () => {
expect(() => parseDuration("abc")).toThrow();
});
});Step 4: Run the suite and let Claude fix failures
Run the tests. If any fail, paste the failure back or just tell Claude to run the test command itself and iterate. Genuine failures often reveal that the test expectation was wrong, so decide case by case whether the code or the test should change.
Result: a single test file in your existing framework, three meaningful cases, and a green run, produced in a couple of minutes instead of a slow manual start.
Watch related tutorials
1:42:18
28:14
41:09
9:47
8:23
52:31