14 minLesson 14 of 18
Coding with ChatGPT
Writing Tests & Documentation
Writing Tests and Documentation with ChatGPT
Tests and documentation are the parts of software development that developers most consistently skip when under time pressure. ChatGPT dramatically lowers the activation energy for both — turning what used to be a chore into a fast, systematic workflow.
Writing Tests
The Test Generation Prompt
The best test generation prompts provide the function/component AND describe what you expect:
Write comprehensive tests for this function.
Function:
[paste function code]
Test cases to cover:
1. Happy path (typical expected input → expected output)
2. Edge cases: [list specific edge cases for this function]
3. Error cases: [what should throw or fail gracefully]
4. Boundary conditions: [min/max values, empty inputs, etc.]
Use [Vitest / Jest / pytest / etc.]
Each test should have a descriptive name that explains what's being tested.
No magic numbers — use named constants for test values.
Example: Testing a Utility Function
Write tests for this TypeScript function using Vitest:
function slugify(text: string): string {
return text
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, '')
.replace(/[\s_-]+/g, '-')
.replace(/^-+|-+$/g, '');
}
Test cases to cover:
- Normal string ("Hello World" → "hello-world")
- Already lowercase
- Multiple spaces
- Special characters (!, @, #, etc.)
- Leading/trailing spaces
- Underscores
- Multiple hyphens
- Empty string
- String that becomes empty after cleaning (e.g., "!!!")
- Unicode characters (test what your team expects — preserve or remove?)
Example: Testing a React Component
Write tests for this React component using Vitest and @testing-library/react:
[paste component code]
Test cases:
1. Renders correctly with required props
2. Shows loading state when isLoading is true
3. Shows error state when there's an error prop
4. Calls onSubmit with correct data when form is submitted
5. Validates required fields before submitting
6. Disables the submit button while submitting
Testing Library guidelines:
- Use getByRole and getByLabelText over getByTestId
- Use userEvent not fireEvent for interactions
- Test behavior, not implementation (no checking state variables)
Example: Testing an API Route
Write integration tests for this Next.js API route:
[paste route handler code]
Test cases:
1. Returns 200 with correct data for valid request
2. Returns 400 with validation errors for invalid input
3. Returns 401 for unauthenticated requests
4. Returns 404 when resource doesn't exist
5. Returns 500 and logs error (don't expose internals to client) for unexpected errors
Use Vitest. Mock the database and auth session.
Show the mock setup.
Writing Documentation
Function/Module Documentation
Write clear documentation for this function.
Function:
[paste code]
Format: JSDoc comment
Include:
- @description — what it does and why someone would use it
- @param — each parameter with type and what it represents
- @returns — what it returns and when
- @throws — what errors it can throw and when
- @example — 2 concrete usage examples
Keep descriptions precise and practical. Don't explain what TypeScript already tells you.
README Documentation
Write a README for this project/package.
Project context:
[describe what it does, who uses it, key features]
Sections to include:
1. Brief description (1-2 sentences, what problem it solves)
2. Requirements (Node version, dependencies)
3. Installation
4. Quick start (get something working in 5 minutes)
5. Configuration (environment variables, options)
6. Core usage with code examples
7. API reference (main functions/exports)
8. Contributing (brief)
Style:
- Clear and scannable
- Code examples over prose where possible
- Assume reader is a developer who wants to get started fast
API Documentation
Write API documentation for these endpoints:
Endpoints:
[paste route handlers or OpenAPI spec]
For each endpoint, document:
- Method and URL
- Authentication required (yes/no, type)
- Request body schema (with required/optional, types, descriptions)
- Query parameters
- Response schema (for 200 and error cases)
- Example request and response
- Common error codes for this endpoint
Format: Markdown that would work in a Readme or docs site
Architecture Documentation
Based on this codebase structure and key files, write an architecture overview document.
Codebase overview:
[describe the main parts of the system]
Key files:
[paste key files or summaries]
Document should cover:
1. System overview (what it does, main components)
2. Tech stack and why each technology was chosen
3. Data flow (how a request flows through the system)
4. Key design decisions and their rationale
5. Directory structure explanation
6. How to extend the system (where to add new features)
Audience: New developers joining the team.
Improving Existing Documentation
Making Docs More Useful
This documentation exists but it's not helpful. Rewrite it to be clearer.
Problems with current docs:
[describe what's wrong — too abstract? missing examples? too long?]
Audience: [developers who are new to this library / junior devs / experienced devs]
Current docs:
[paste]
Improvements to make:
- Add concrete code examples for each concept
- Replace abstract explanations with specific, practical descriptions
- Add a "when would I use this?" section
- Cut anything that doesn't help someone use the API
Auditing Documentation
Audit this documentation for quality. Check:
1. Are there any obvious gaps (things that should be documented but aren't)?
2. Are code examples accurate and up to date?
3. Is anything described in a confusing or misleading way?
4. What would a new developer struggle to understand from this?
5. Are all the parameters and return values documented?
[paste documentation]
Generating Test Data
Generate test data for our database. We need realistic fake data for:
Tables and their schemas:
[paste schema]
Generate:
- 5 users with realistic names, emails, and created_at dates
- 10 courses with realistic titles, descriptions, and prices
- 20 enrollments linking users to courses
Format as SQL INSERT statements.
Use realistic but clearly fake data (no real names or emails).
Writing Changelog Entries
Write a changelog entry for this set of changes.
Changes made in this release:
[paste git log output or describe changes]
Format: Keep a Changelog style (https://keepachangelog.com)
Sections to use: Added, Changed, Deprecated, Removed, Fixed, Security
Audience: Developers using this as a library or API — focus on changes
that affect how they use it, not internal implementation details.
The Test-First Approach
For complex features, use ChatGPT to write tests before the implementation:
I'm building a feature: [describe feature]
Before implementing it, write the test cases that the implementation must pass.
Think through:
- What are all the ways this feature can be used correctly?
- What invalid inputs or edge cases need to be handled?
- What should fail gracefully vs. throw an error?
- What interactions with other parts of the system need to be tested?
Write the test file with all the test cases (but you can leave the assertions
as TODO comments or placeholders — I'll fill them in after implementing).
Writing tests first clarifies the requirements before you write a line of implementation code.
Next lesson: Data analysis — using ChatGPT to analyze, visualize, and interpret data.
📱
Get Notes Free →Get this course's notes on Telegram!
Free cheat sheets, summaries & practice exercises