Skip to content

Menu

Playbooks

Add tests for an existing function

Document a small function's current behavior, then use an incorrect expectation and a deliberate mutation to verify that the tests are trustworthy.

min read
20
Level
Intermediate
Last verified

This playbook helps you add characterization tests to a small function that is already in use but has no tests. First, document what the code currently does; then use tests to protect those observable behaviors. This creates a safety net before a refactor or bug fix, but it does not determine whether every existing behavior is correct.

If you import a code folder into Gemini Apps, first confirm which files the model actually received. Official guidance warns that details may be missed in large source sets. Whatever interface you use, review and run all generated tests yourself. Google also reminds users that they are responsible for the results of using generated code.

In plain English: Lock down the current behavior before discussing changes

Section titled “In plain English: Lock down the current behavior before discussing changes”

Characterization tests are like an evidence-backed snapshot of a legacy function. Assertions should come from the source code, confirmed calling conventions, or direct observation—not from the “ideal behavior” implied by the function’s name. If the current behavior conflicts with the requirements, record it as a separate bug. Do not quietly change the implementation while “adding tests.”

Weak prompt:

Add a complete test suite for normalizeLabel, and clean up the implementation while you're at it.

Better prompt:

Do not change the code or generate tests yet. Derive the current behavior of normalizeLabel one item at a time.
Cover ordinary input, nullish values, blank input, repeated spaces, and non-string edge cases. Cite source-code evidence for each item.
After I confirm the behavior inventory, generate only the node:test test file.

Complete example: Document the current behavior of a label-formatting function

Section titled “Complete example: Document the current behavior of a label-formatting function”

The following is the complete synthetic exercise directory. Assume the function is already in use but has no requirements document or tests:

label-tools/
├── package.json
└── src/
└── normalize-label.js
package.json
{
"type": "module",
"scripts": {
"test": "node --test"
}
}
src/normalize-label.js
export function normalizeLabel(input) {
if (input == null) return '';
return String(input).trim().toLowerCase().replaceAll(' ', '-');
}

The known environment is Node 24 with ECMAScript modules, and the test command is node --test.

  • In the first round, do not modify any files. Analyze only package.json and src/normalize-label.js.
  • In the second round, add only test/normalize-label.test.js. Do not change the source function, export name, package.json, or dependencies.
  • The later mutation check may temporarily break one line in src/normalize-label.js, but you must restore it after verification.
  • “Improvements” with no basis in the requirements may be listed only as items to confirm. Do not turn them into assertions about current behavior.

First prompt: List behaviors and edge cases

Section titled “First prompt: List behaviors and edge cases”
Analyze this small function, which has existing behavior but no tests. In the first round, do not generate tests,
modify code, or claim that you ran any commands.
[Goal]
Build an inventory of current behavior as the basis for later characterization tests.
[Workflow]
1. List the files you actually received. If anything is missing or truncated, stop instead of guessing.
2. Explain the null and undefined branch and the string-conversion chain in evaluation order.
3. Output a table: input | output derived from the current code | direct source-code evidence | whether product confirmation is needed.
4. Check null, undefined, ' ', ' North Star ', 'North Star', and 0 one by one.
5. Distinguish “facts about the current code” from “behavior you think would be more reasonable.”
6. End with any contracts that still need maintainer confirmation. Do not provide a patch.
[Files]
Paste package.json and src/normalize-label.js here.

After manually checking the function against the source code, the behavior inventory should be:

Input Current output Direct evidence Contract status
null '' input == null is true Derivable from the source; long-term support still needs confirmation
undefined '' input == null is true Derivable from the source; long-term support still needs confirmation
' ' '' trim() produces an empty string Derivable from the source
' North Star ' 'north-star' Trims leading and trailing whitespace, lowercases the text, then replaces ordinary spaces Derivable from the source
'North Star' 'north--star' replaceAll(' ', '-') replaces each of the two ordinary spaces Derivable from the source; whether to collapse them must be confirmed separately
0 '0' String(0) first produces '0' Derivable from the source; the valid input range needs confirmation

The key point to check manually is that the current result for 'North Star' really does contain two hyphens. Collapsing repeated spaces into one hyphen may be a reasonable new requirement, but neither the source code nor the existing materials support it.

The behavior inventory below has been manually checked against the source. Now add only
test/normalize-label.test.js. Do not modify any other file.
Confirmed current outputs:
- null -> ''
- undefined -> ''
- ' ' -> ''
- ' North Star ' -> 'north-star'
- 'North Star' -> 'north--star'
- 0 -> '0'
[Requirements]
1. Use node:test and node:assert/strict.
2. The null, undefined, and blank-input cases produce the same output, so they may share one test.
3. Test names must describe observable behavior, not what “would be more reasonable.”
4. Do not change the implementation to satisfy the tests.
5. Output the complete test file.
6. End with the command to run and contracts that still need confirmation, but do not claim that you ran it.
test/normalize-label.test.js
import test from 'node:test';
import assert from 'node:assert/strict';
import { normalizeLabel } from '../src/normalize-label.js';
test('returns an empty label for nullish or blank input', () => {
assert.equal(normalizeLabel(null), '');
assert.equal(normalizeLabel(undefined), '');
assert.equal(normalizeLabel(' '), '');
});
test('trims, lowercases, and replaces an ordinary space', () => {
assert.equal(normalizeLabel(' North Star '), 'north-star');
});
test('replaces each repeated ordinary space separately', () => {
assert.equal(normalizeLabel('North Star'), 'north--star');
});
test('converts zero to text', () => {
assert.equal(normalizeLabel(0), '0');
});

After saving the file, run node --test. The minimum expected result is tests 4, pass 4, and fail 0. This shows only that the tests agree with the current implementation. Whether null and 0 are supported long-term must still be confirmed through the calling convention or with the maintainer.

Expected failure: The test expects the wrong result

Section titled “Expected failure: The test expects the wrong result”

To practice spotting an assumption disguised as an assertion, temporarily change the repeated-space test to the following:

test('collapses repeated ordinary spaces', () => {
assert.equal(normalizeLabel('North Star'), 'north-star');
});

Run node --test again. This is an expected failure: the minimum result should be tests 4, pass 3, and fail 1. The failure details should show 'north--star' as the actual value and 'north-star' as the expected value.

This red result is not evidence of a regression in the function. It means the test turned an unconfirmed preference into a claim about current behavior. After checking replaceAll(' ', '-'), restore the original test name and the 'north--star' assertion. If the product really does need to collapse spaces, open a separate behavior-change task and write a requirements test first.

Verification: Use a one-line mutation to make sure the tests turn red

Section titled “Verification: Use a one-line mutation to make sure the tests turn red”

First, restore the correct assertion and confirm that all 4 tests pass. Then temporarily break the source:

return String(input).trim().toLowerCase().replaceAll(' ', '-');
return String(input).trim().toUpperCase().replaceAll(' ', '-');

Run node --test. The minimum expected result is tests 4, pass 2, and fail 2. The ordinary-label and repeated-space cases should fail, with actual values of 'NORTH-STAR' and 'NORTH--STAR', respectively. If everything still passes, the tests do not protect the case-conversion behavior.

Immediately after verification, restore toLowerCase(), confirm that the mutation no longer appears in the diff, and run node --test once more. All 4 tests must pass again. Then follow the project documentation to run the full test suite, type checking, and continuous integration (CI) checks.

This page has not run the exercise repository for you. Its source-checked status means only that the product facts were verified; it does not mean this code is run-tested in your environment.

  • Every output in the behavior inventory can be traced to a specific expression or confirmed calling convention.
  • Test assertions document current behavior. They do not treat “repeated spaces should be collapsed” as an established fact.
  • The final diff adds only test/normalize-label.test.js, with no incidental refactor of the source function.
  • The incorrect expectation fails as intended because the actual value differs from the assumed value.
  • The deliberate mutation makes the two relevant tests turn red, and all tests turn green again after the source is restored.
  • The Node version, exact command, and actual output have been recorded.
  • The full test suite, type checking, and CI have been run, or any skipped checks and the reasons for skipping them have been recorded explicitly.
  • The test materials contain no secrets, production configuration, customer data, or private conversations.
  • The first run fails: Check the import path, Node version, input characters, and actual value first. Do not change the source function merely to manufacture a passing result.
  • Current behavior conflicts with the requirements: Record the conflict as a bug, preserve the evidence of current behavior, and write the requirements test and fix in a separate task.
  • The model also changes the source: Discard the out-of-scope patch and restate that only test/normalize-label.test.js may be added.
  • The incorrect expectation unexpectedly passes: Check whether node --test actually discovered the test and whether the input really contains two ordinary spaces.
  • Everything still passes after the mutation: Add an input that distinguishes the output before and after the mutation, confirm that the test runs, and try again.
  • You forget to restore the mutation: Inspect the diff first, restore only that line, and rerun the tests. Do not use a command that would overwrite other uncommitted work.
  • Too much material or truncated input: Provide only the target function, its direct calling conventions, the test configuration, and relevant existing tests. Ask the model to report its file inventory first.
  • Production code or sensitive data is involved: Redact the materials first and follow your organization’s rules. Generated tests still require human review.

Next: If the current behavior really is a bug, continue to Locate and fix a bug. When you are ready to review a change, read Have Gemini review a change. If the test command itself fails, see Troubleshooting.