An AI assistant can write a working function in seconds, and that speed creates a new problem. You now have code you did not write, in a style you did not choose, with edge cases you did not think about. Writing unit tests for ai-generated code is how you check that code before it reaches production. A test forces you to state what the function should do, then proves whether it does it.
This guide shows a practical way to test code an assistant produced: read it first, pick the behaviour worth testing, and write the tests yourself where it matters. The goal is not 100 percent coverage. It is a small set of tests that catch the mistakes AI assistants make most often.
Why generated code fails in ways you do not expect
AI assistants are good at producing code that looks right, with a clear name, sensible variables, and a confident docstring. That surface quality hides a real risk. The assistant may have guessed at a detail your prompt left out, such as how to handle a null value, an empty list, or a date in a different timezone. It may have copied a pattern from a common example that does not fit your data, or used a library call in a way your version does not support.
Your own code fails too, but you usually know where you were unsure. With generated code, you have no memory of the trade-offs, so you cannot tell from reading alone whether the code is careful or just confident. Tests close that gap: each test records one decision about correct behaviour, and a failing test shows where the assistant guessed wrong. Testing ai-generated code also guards against silent drift. If the assistant regenerates the function next week with a small change in behaviour, a test that passed yesterday and fails today points straight at the change.
How to write unit tests for ai-generated code, step by step
Work through these steps in order. Writing the test is when you learn what the code actually does.
1. Read the generated code line by line
Before you write a single test, read the function and trace it with a real input. Note every branch, every early return, and every place it touches something outside itself, such as a database, a file, or a network call. If a line confuses you, do not skip it. Ask the assistant to explain it, then check the explanation against the code. If you cannot explain what a function does in one sentence, you are not ready to test it.
While you read, list the inputs that could break it: empty strings, zero, negative numbers, very large lists, and missing fields. That list is also your test plan.
2. Start from behaviour, not from the code
Write down what the function should do in plain words before you look at how it does it. For a discount function, the behaviour might be: a regular customer pays full price, a member gets 10 percent off, and an order over a set amount gets free shipping. Each sentence becomes one test. If you copy the code structure into your tests instead, you will test the implementation rather than the requirement, and a wrong implementation will pass its own wrong tests.
Keep each test focused on one behaviour. A test named test_member_discount should check the discount and nothing else. If you are new to this style, our beginner’s guide to unit testing with Jest shows the basic structure of a small, focused test file.
3. Cover the edges and the errors
The happy path is the least useful test for generated code, because that is the path the assistant already checked in its head. Spend most of your effort on the cases around it: an empty input, a missing optional field, and a value at the exact boundary of a rule, such as the order total that just qualifies for free shipping and the one just below it. Then test the error paths: the wrong input type, a missing required field, a failed external call. The function should fail in a clear way, with an error you can recognise, not by returning a wrong answer quietly.
When you write unit tests, pick the framework your project already uses rather than the one the assistant suggests. If your team has not settled on one, our comparison of Jest, Vitest, and Mocha covers the practical differences that matter for a JavaScript project.
4. Mock the boundaries, not the logic
Replace databases, APIs, and file access with test doubles so the test runs fast and gives the same result every time. Do not mock the function you are testing, or the small helpers inside it. Mock what crosses a boundary, test everything else for real. If a function is hard to test without mocking its own internals, it probably does too much, and splitting it will help both the code and the tests.
What to do when the assistant writes the tests too
Letting the assistant write the tests saves time, but it creates the same problem as letting it write the code: you end up with output you have not checked. Assistant-written tests often repeat the code’s mistakes, because the expected values came from the code instead of the requirement. Some are tautologies, asserting that a function returns whatever it returned. Others show high coverage while missing the important cases, because the assistant tested the happy path and none of the edges.
Use the assistant as a starting point, not as the author of record. Ask it to draft tests from your list of behaviours, then review each one the way you would review code from a junior colleague. Check that every expected value comes from the requirement, not from running the code and copying the output. Delete any test that would pass even if the function were wrong, and add the edge cases yourself. AI code testing works best as a pair activity: the assistant drafts, you decide what counts as correct. Our code review checklist for AI-assisted pull requests covers the same kind of check for generated code, and tests deserve the same pass.
Common failure patterns to test for
- Off-by-one errors. A loop stops one item early, or a range includes one item too many. Test lists with zero, one, and two items, plus the exact boundary value.
- Null and missing data. The code assumes a field is always present. Test missing, null, and empty values for every optional field.
- Wrong defaults. A default looks sensible but does not match your rules. Call the function without the optional argument and check the result.
- Date and time handling. Timezones and date formats are handled loosely. Test dates near midnight, month ends, and a second timezone.
- Silent rounding. Money loses cents through rounding in the wrong place. Test amounts that produce fractions of a cent.
- Untested error paths. Failures return a plausible wrong answer instead of an error. Test invalid input and a failed external call.
A short example
Take a generated function that applies a discount. The code looks fine, but a test for the boundary tells a different story:
test("free shipping starts at exactly 50", () => {
expect(totalWithShipping(50, false)).toBe(50);
expect(totalWithShipping(49.99, false)).toBe(54.99);
});
test("member discount applies before the shipping check", () => {
expect(totalWithShipping(55, true)).toBe(49.50);
});
The first test checks the boundary on both sides. The second checks the order of operations, which is exactly the detail an assistant can get wrong while producing code that reads well. Neither test cares how the function is written inside. Write tests at this level and the suite stays useful after rewrites.
Keep the tests after the code lands
A test that only runs once on your laptop is a note, not a safety net. Add the new tests to your normal test command and make sure they run in continuous integration before merge. If a test is slow or depends on the network, fix that before you merge it. If a test fails in CI but passes on your machine, treat that as a real signal: generated code often depends on an assumption about the environment, such as a timezone or a library version, and the gap between your machine and CI is where that shows up.
Unit tests are not the whole story. They check one function at a time, and some bugs only appear when functions work together. Our guide to integration testing explains where unit tests stop and integration tests take over.
When a test fails after a later change, first ask whether the code changed or the requirement changed. If the requirement changed, update the test and say why in the commit message. If the code changed by accident, the test just did its job.