Overview
Test-Driven Development (TDD) with LLMs combines the red-green-refactor cycle with AI code generation. You write the test (specification), the LLM writes the implementation. This produces more reliable AI-generated code because the test serves as an unambiguous contract.
The TDD + AI Workflow
- •RED: Write a failing test that describes the desired behavior
- •GREEN: Provide the test to the LLM and ask it to write passing code
- •RUN: Execute the test to verify it passes
- •ITERATE: If it fails, share the error with the LLM to fix
- •REFACTOR: Once green, ask the LLM to improve the code while keeping tests green
- •REPEAT: Add the next test case and repeat
Example Prompt
Here is a failing test. Write the implementation that makes it pass.
```typescript
import { describe, it, expect } from 'vitest';
import { parseSearchQuery } from './search.ts';
describe('parseSearchQuery', () => {
it('parses simple terms', () => {
expect(parseSearchQuery('hello world')).toEqual({
terms: ['hello', 'world'],
filters: {},
});
});
it('extracts key:value filters', () => {
expect(parseSearchQuery('type:bug urgent')).toEqual({
terms: ['urgent'],
filters: { type: 'bug' },
});
});
});
```
Write only the parseSearchQuery function. Export it as a named export.Tips
Start with the simplest test case, add complexity incrementally, always run tests between iterations, and let the LLM suggest edge case tests you may have missed. TDD with AI is one of the most reliable ways to get correct generated code.