--- name: write-unit-tests description: Writes focused unit tests for a named file, function, or the functions changed since the last commit, matching the project's existing test framework, layout and helpers, then runs the new tests. Use when the user asks to add, write or improve unit tests. --- # Write unit tests Target: `$ARGUMENTS`. If empty, use functions and methods changed in `git diff HEAD`. If that is empty too, ask what to test. ## 1. Detect the setup Identify the runner from project files. Common signals: - `package.json` devDependencies or scripts mentioning `vitest` or `jest`; config files `vitest.config.*`, `jest.config.*`. - `pyproject.toml` / `pytest.ini` / `conftest.py` for pytest. - `go.mod` for Go (`*_test.go` next to the source). - `phpunit.xml` or `tests/Pest.php` for PHPUnit or Pest. - `.rspec` or `spec/` for RSpec. If the runner is unclear, ask instead of guessing. ## 2. Learn local conventions Read two or three existing test files closest to the target. Note: - Where test files live and how they are named. - Shared fixtures, factories, builders and custom matchers. - How the project fakes time, network and the database. - Assertion style and how tests are grouped. Reuse existing helpers. Do not add new test dependencies without asking. ## 3. Plan the cases Before writing, list the behaviors to cover, in one line each: - Main success path. - Boundaries (empty, one, many; min and max; zero and negative). - Invalid input and the expected error. - Branches visible in the code that the above do not hit. Prefer five meaningful cases over twenty redundant ones. ## 4. Write the tests - One behavior per test. Name the test after the behavior, not the function. - Arrange, act, assert. Keep setup visible in the test unless a shared fixture already exists. - Mock only external boundaries: network, clock, randomness, filesystem, third-party SDKs. Never mock the unit under test. - Assert on outputs and observable side effects, not on private internals. - Do not use snapshots unless the project already does for this kind of code. ## 5. Run and iterate Run only the new or changed test file, for example: - `npx vitest run ` / `npx jest ` - `pytest -q` - `go test ./ -run ` - `./vendor/bin/pest ` / `./vendor/bin/phpunit ` If a test fails: - If the test is wrong, fix the test. - If the source looks wrong, stop. Report the suspected bug with the failing input and expected vs actual output. Do not change the assertion to match the current output, and do not edit source without permission. ## 6. Report List the test file(s) written, the cases covered, the exact command to run them, the result, and any suspected bugs.