Vibe coding with Claude Code course · Module 5: Reddit clone
The crew votes: test first, code second
In this lesson15
Ahoy! An argument is raging on deck: sail to Tortuga or head north for the gold from the wreck. In this location you build Crew Council, a pirate forum in the style of Reddit, where the crew votes for and against ideas and the best ones float to the top on their own. The voting rules are easy to break quietly, so Claude Code will write the exam first and only then the code that passes it.
What you will learn
- ask Claude Code to set up tests according to the Next.js documentation and check in Cursor what it added;
- order the tests first, watch them fail, and only then get the code that passes them;
- demand proof: a command and its output instead of the sentence "the tests pass";
- spot an agent that fixes the test instead of the code;
- keep the votes in the list state so that sorting can see them.
A new port: the crew-council project
The forum is a separate app, so it gets its own project. You create it with the command from lesson 1_2, changing only the name. Before you click Yes, compare the command with this one:
npx create-next-app@latest crew-council --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npmThen comes the familiar loop: a session in the crew-council folder, npm run build as proof, a short CLAUDE.md with the @AGENTS.md import as in lesson 1_7, and the first commit.
The problem: rules that are easy to break
A pirate's vote has three states: for ("up"), against ("down") or none (null). A post's score is the votes for minus the votes against. The council's rules are:
- a plus or a minus with no earlier vote adds one vote;
- a second click on the same button undoes the vote;
- changing from plus to minus removes the vote for and adds a vote against, so the score drops by 2, and the other way round it rises by 2.
That is six transitions, and each can be broken in a way that leaves the page looking fine. By clicking you will check two or three; a test checks all of them in a fraction of a second.
A test in one paragraph
A test is a small program that calls your code with fixed data and compares the result with the expected one, like a contract: "the post has 10 votes for, after a click on plus it must have 11". The test tool runs all the contracts and reports which ones passed, and Claude can run them itself. The official Claude Code best practices advise giving it something that answers "passes" or "fails", and always asking for proof: the command and its output.
Request for Claude Code: setting up tests
The Next.js documentation describes four tools: Jest and Vitest for unit tests, Cypress and Playwright for tests of whole paths in the browser. We pick Vitest because, according to that documentation, it needs just one short config file, while Jest also needs the npm init jest wizard, the ts-node package and manual mapping of the @/ shortcut.
Request for Claude Code:
Set up unit tests with Vitest in Crew Council following the Next.js
documentation (node_modules/next/dist/docs/01-app/02-guides/testing/vitest.md):
the packages, vitest.config.mts and a "test" script in @package.json.
Do not add example tests. If npm reports a version conflict, show me
the error and propose a fix before you use --force or --legacy-peer-deps.
At the end run npm run test -- --run and show the result.This is the documentation the wizard left in the project, matching your version of Next.js.
What Claude did: a version conflict
The installation following the documentation stopped on an error. Here are its most important lines:
npm error code ERESOLVE
npm error While resolving: vitest@5.1.0
npm error Found: @types/node@20.19.43
npm error peerOptional @types/node@"^22.0.0 || >=24.0.0" from vitest@5.1.0
npm error Fix the upstream dependency conflict, or retry this command with --force or --legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution.ERESOLVE means npm cannot pick versions that fit together. Vitest 5 expects Node.js types in version 22 or newer, and the wizard put @types/node in version 20 into the project (as of November 2026). The last line tempts you with a shortcut: --force and --legacy-peer-deps tell npm to ignore the conflict and install "potentially broken" dependencies. The right fix is types that match your Node.js (check it with node -v): on the Node 26 line Claude proposes npm install -D @types/node@26. After that the installation went through without errors.
What Claude did: the configuration
Open the Source Control panel in Cursor and click package.json. Five packages were added to devDependencies: vitest, the tool itself, @vitejs/plugin-react, which understands JSX, jsdom, a pretend browser, and @testing-library/react and @testing-library/dom for component tests. A "test": "vitest" line was added to scripts. Now open vitest.config.mts:
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
resolve: {
tsconfigPaths: true,
},
test: {
environment: "jsdom",
},
});environment: "jsdom" turns on the pretend browser. resolve.tsconfigPaths teaches Vitest the @/ shortcut from tsconfig.json, so a test imports @/lib/votes like the rest of the project. The Next.js documentation does this with the vite-tsconfig-paths package, but on the first run Vite printed a warning that it can do this itself and named this option. Claude swapped the plugin for the option and uninstalled the package. A warning is not an error, but always read it, because it often tells you how to do something more simply.
With no tests the command ends with the message No test files found, exiting with code 1: the tool works and waits for .test.ts files, and the first one appears in a moment.
The test command in CLAUDE.md
npm run test in your terminal starts in watch mode: the tests rerun after every file change, and the command runs until Ctrl+C. So ask: "Add the test command to CLAUDE.md, single run". A line appears in the commands section:
- Tests: npm run test -- --run (Vitest, a single run without watch mode)The two dashes pass the rest of the command to Vitest, and --run turns watching off.
Request for Claude Code: tests first
Now you turn the council's rules into an exam. The order is deliberate: the tests come before the code, so they describe your rules, not whatever happened to come out of the code.
Crew Council: a post has upvotes, downvotes and userVote ('up', 'down' or
null). Define the Post type and sample posts in lib/posts.ts. First write
the tests of the applyVote(post, clicked) function in lib/votes.test.ts:
plus, minus, a second click undoes the vote, changing from plus to minus
and from minus to plus (the score changes by 2), and the post you pass in
stays unchanged. Leave an empty skeleton of the function in lib/votes.ts.
Run the tests: they must not pass. Show the command and the result, then
stop before the code."Stop" gives you time to read the tests before Claude fits the code to them. The empty skeleton makes the tests fail on comparing results, not on a missing file.
What Claude wrote: the test
Open lib/votes.test.ts in Cursor and read it before the code. The Post type from lib/posts.ts has a title, body, author, community, a date as ISO text and three vote fields. At the top of the test stands the post all cases work on: 10 votes for, 2 against, userVote: null. The first case:
it("plus with no earlier vote adds an upvote", () => {
expect(applyVote(post, "up")).toMatchObject({ upvotes: 11, downvotes: 2, userVote: "up" });
});it describes one case with a sentence, and expect compares the result with the expected one. toMatchObject checks only the listed fields: 11 for, 2 against, a vote for. All the cases sit in a describe("applyVote", ...) block, which groups the tests of one function. This is how a change of mind looks:
it("changing from minus to plus raises the score by 2", () => {
const voted = { ...post, downvotes: 3, userVote: "down" as const };
const after = applyVote(voted, "up");
expect(after).toMatchObject({ upvotes: 11, downvotes: 2, userVote: "up" });
expect(score(after)).toBe(score(voted) + 2);
});voted is the same post after a vote against, and as const tells TypeScript that "down" is exactly that value, not any text. The numbers in the expectations come from the council's rules and are typed by hand, not computed with the same formula as the function. The file has seven cases: six transitions and one that checks that the original post did not change.
Red: the tests fail
Claude ran the command from CLAUDE.md and showed the result. Here is its middle, without the header and without the details of each failure, which Vitest prints below:
❯ lib/votes.test.ts (7 tests | 6 failed) 5ms
❯ applyVote (7)
× plus with no earlier vote adds an upvote 3ms
× minus with no earlier vote adds a downvote 0ms
× a second click on plus undoes the vote 0ms
× a second click on minus undoes the vote 0ms
× changing from plus to minus lowers the score by 2 0ms
× changing from minus to plus raises the score by 2 0ms
Tests 6 failed | 1 passed (7)Six failures is good news: each of those tests really checks something. The seventh passed because the empty skeleton returns the post unchanged; a rule test that passes on an empty skeleton would not guard anything. In the failure details the expected fields have a minus sign and the received ones a plus.
Green: a function made to the tests
Now the request: "Write applyVote so that the tests pass. Do not change the tests. Show the command and the result". Open lib/votes.ts:
export function applyVote(post: Post, clicked: "up" | "down"): Post {
const nextVote: Vote = post.userVote === clicked ? null : clicked;
const upvotes = post.upvotes - countSide(post.userVote, "up") + countSide(nextVote, "up");
const downvotes =
post.downvotes - countSide(post.userVote, "down") + countSide(nextVote, "down");
return { ...post, upvotes, downvotes, userVote: nextVote };
}The first line sets the new vote: the same button a second time gives null, a different one gives the clicked one. Then the counters take off the old vote and add the new one. countSide is a small function in this file that returns 1 when the vote is on a given side and 0 otherwise. The last line builds a new object with a spread, so the post you passed in stays untouched. Next to it stands score(post), that is post.upvotes - post.downvotes. The result of running again:
Test Files 1 passed (1)
Tests 7 passed (7)This is proof: a command and its output, not the sentence "it should work".
Captain's review
- A test fixed so that it passes. This is the most dangerous mistake an agent makes with tests. We checked a function that, on a change of mind, adds the new vote but does not take off the old one: two tests fail. An agent that cares about a green result can then fix the expectation instead of the code:
- expect(after).toMatchObject({ upvotes: 11, downvotes: 2, userVote: "up" });
- expect(score(after)).toBe(score(voted) + 2);
+ expect(after).toMatchObject({ upvotes: 11, downvotes: 3, userVote: "up" });
+ expect(score(after)).toBe(score(voted) + 1);The tests are green again, and the council counts one pirate twice. That is why you look into Source Control after every turn: a change in a .test.ts file that you did not ask for is a signal to stop. Add a trap to CLAUDE.md: "A test that fails is fixed in the code; you do not change the expected values without my consent". From lesson 1_7 you know that this is a hint, not a lock, so you read the diff anyway.
Six transitions. Count the cases: from none to plus and to minus, undoing plus and minus, a change in both directions. A missing case is a rule nobody guards.
A mirror test. An expectation copied from the function, for example
expect(score(after)).toBe(after.upvotes - after.downvotes), always passes, even when the votes are counted wrongly.Run it yourself. Type
! npm run test -- --runin the session, as in lesson 0_3.
Votes in the list, not in the button
Time for the screen. A typical agent idea is a button with its own useState for the counters: the number on the button changes, but the list of posts does not know about it, so sorting by score does not move the post. This is lesson 2_3 in a new costume: data needed in two places is held by a shared parent.
Build the Crew Council home page. components/Feed.tsx holds the posts
in state and changes them through applyVote from @lib/votes.ts.
components/VoteButtons.tsx has no state of its own: it gets score,
userVote and an onVote function. Do the hot, new and top sorting as
a pure sortPosts function in lib/sort.ts, with tests first. At the end
the tests, lint and build.The ban on state in VoteButtons is the whole fix: the button only says what was clicked, and whoever holds the list does the counting. Open components/Feed.tsx. The heart is the function that changes one post:
const [posts, setPosts] = useState(initialPosts);
const [sortMode, setSortMode] = useState<SortMode>("hot");
const handleVote = (postId: string, clicked: "up" | "down") => {
setPosts((prev) =>
prev.map((post) => (post.id === postId ? applyVote(post, clicked) : post)),
);
};
const visiblePosts = sortPosts(posts, sortMode);map replaces only the post with the matching id. The order has no state of its own: visiblePosts is computed on every render from the current votes. The ▲ button in VoteButtons has onClick={() => onVote("up")}, aria-label="Upvote" for the screen reader and aria-pressed, which says whether the vote is cast.
In lib/sort.ts there are three modes: new orders by date, top by score, and hot combines the two with a formula from the ranking code that Reddit published as open source:
export function hotScore(post: Post): number {
const s = score(post);
const order = Math.log10(Math.max(Math.abs(s), 1));
const seconds = Date.parse(post.createdAt) / 1000 - 1134028003;
return Math.sign(s) * order + seconds / 45000;
}Math.log10 computes the order of magnitude of the score: 10 votes give 1 and 100 give 2. 1134028003 is a constant from Reddit's code, a moment in December 2005 in seconds. Every 45,000 seconds, that is 12.5 hours of youth, weighs as much as ten times more votes. The formula does not ask the clock, only the post's date, so it is a pure function that can be tested. sortPosts sorts a copy, [...posts], because sort changes the array it works on.
The check in the browser: run npm run dev, choose top and vote for the second post. In ours the first two had a tie of 90 to 90, so one vote moved the second to the top, and a change to minus left it with a score of 89.
Next step
When the tests, lint and build are green, ask for a commit, for example "Voting: applyVote with tests, vote state in Feed". Then another small step in the same loop:
Add an upvotePercent(post) function in @lib/votes.ts: the percentage
of votes for, rounded to a whole number. Tests first: 85 for and 15
against gives 85, no votes gives 0. Run them before the code and after
it, and show both results.Claude computes Math.round(post.upvotes / (post.upvotes + post.downvotes) * 100) and first checks that the sum is not zero, because division by zero would give NaN. In the editor below waits a feed with votes in the list state and a small applyVote check: vote and watch the post change places.
Remember: the captain writes down the council's rules, the test guards them at every vote, and whoever fixes the test instead of the code turns the compass to fit the course.
Code for this lesson: App.jsx
// Crew Council: votes live in the list state, the button only calls a function
import { useState } from 'react';
const startPosts = [
{ id: 'p1', title: 'Sail to Tortuga or head north?', upvotes: 120, downvotes: 30, userVote: null, createdAt: '2026-11-13T08:00:00.000Z' },
{ id: 'p2', title: 'Treasure map with an X on Skull Island', upvotes: 95, downvotes: 5, userVote: null, createdAt: '2026-11-14T06:00:00.000Z' },
{ id: 'p3', title: 'How do you patch a hull with tar?', upvotes: 40, downvotes: 2, userVote: null, createdAt: '2026-11-14T09:30:00.000Z' },
{ id: 'p4', title: 'The Kraken sank our longboat', upvotes: 60, downvotes: 15, userVote: null, createdAt: '2026-11-12T18:00:00.000Z' },
];
const score = (post) => post.upvotes - post.downvotes;
// 1 when the vote is on this side, otherwise 0
const countSide = (vote, side) => (vote === side ? 1 : 0);
function applyVote(post, clicked) {
const nextVote = post.userVote === clicked ? null : clicked;
return {
...post,
upvotes: post.upvotes - countSide(post.userVote, 'up') + countSide(nextVote, 'up'),
downvotes: post.downvotes - countSide(post.userVote, 'down') + countSide(nextVote, 'down'),
userVote: nextVote,
};
}
// Formula from Reddit's ranking code: order of magnitude of the score plus the age of the post
function hotScore(post) {
const s = score(post);
const order = Math.log10(Math.max(Math.abs(s), 1));
const seconds = Date.parse(post.createdAt) / 1000 - 1134028003;
return Math.sign(s) * order + seconds / 45000;
}
function sortPosts(posts, mode) {
const copy = [...posts];
if (mode === 'new') return copy.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
if (mode === 'top') return copy.sort((a, b) => score(b) - score(a));
return copy.sort((a, b) => hotScore(b) - hotScore(a));
}
// A small check: the same cases as in lib/votes.test.ts
const base = { upvotes: 10, downvotes: 2, userVote: null };
const checks = [
{ name: 'plus with no earlier vote', actual: applyVote(base, 'up'), expected: [11, 2, 'up'] },
{ name: 'minus with no earlier vote', actual: applyVote(base, 'down'), expected: [10, 3, 'down'] },
{ name: 'second click on plus undoes the vote', actual: applyVote({ ...base, upvotes: 11, userVote: 'up' }, 'up'), expected: [10, 2, null] },
{ name: 'second click on minus undoes the vote', actual: applyVote({ ...base, downvotes: 3, userVote: 'down' }, 'down'), expected: [10, 2, null] },
{ name: 'plus to minus: score -2', actual: applyVote({ ...base, upvotes: 11, userVote: 'up' }, 'down'), expected: [10, 3, 'down'] },
{ name: 'minus to plus: score +2', actual: applyVote({ ...base, downvotes: 3, userVote: 'down' }, 'up'), expected: [11, 2, 'up'] },
];
const passes = ({ actual, expected }) =>
actual.upvotes === expected[0] && actual.downvotes === expected[1] && actual.userVote === expected[2];
function VoteButtons({ score, userVote, onVote }) {
return (
<div className="flex flex-col items-center gap-1">
<button
type="button"
onClick={() => onVote('up')}
aria-label="Upvote"
aria-pressed={userVote === 'up'}
className={userVote === 'up' ? 'text-orange-600' : 'text-gray-400 hover:text-orange-600'}
>
▲
</button>
<span className="text-sm font-bold">{score}</span>
<button
type="button"
onClick={() => onVote('down')}
aria-label="Downvote"
aria-pressed={userVote === 'down'}
className={userVote === 'down' ? 'text-blue-600' : 'text-gray-400 hover:text-blue-600'}
>
▼
</button>
</div>
);
}
export default function App() {
const [posts, setPosts] = useState(startPosts);
const [sortMode, setSortMode] = useState('top');
const handleVote = (postId, clicked) => {
setPosts((prev) => prev.map((post) => (post.id === postId ? applyVote(post, clicked) : post)));
};
const visiblePosts = sortPosts(posts, sortMode);
return (
<div className="min-h-screen bg-gray-100 p-4 text-gray-900">
<div className="mx-auto max-w-xl space-y-3">
<h1 className="text-2xl font-bold">Crew Council</h1>
<div className="flex gap-2">
{['hot', 'new', 'top'].map((mode) => (
<button
key={mode}
type="button"
onClick={() => setSortMode(mode)}
aria-pressed={sortMode === mode}
className={sortMode === mode ? 'rounded bg-orange-600 px-3 py-1 text-white' : 'rounded px-3 py-1 hover:bg-gray-200'}
>
{mode}
</button>
))}
</div>
{visiblePosts.map((post) => (
<article key={post.id} className="flex gap-3 rounded-lg border border-gray-200 bg-white p-3">
<VoteButtons score={score(post)} userVote={post.userVote} onVote={(clicked) => handleVote(post.id, clicked)} />
<h2 className="self-center font-semibold">{post.title}</h2>
</article>
))}
<section className="rounded-lg bg-white p-3 text-sm">
<h2 className="mb-2 font-bold">applyVote check</h2>
<ul className="space-y-1">
{checks.map((check) => (
<li key={check.name} className={passes(check) ? 'text-green-700' : 'font-semibold text-red-700'}>
{passes(check) ? 'PASSED' : 'FAILED'}: {check.name}
</li>
))}
</ul>
<p className="mt-2 text-gray-600">
Break applyVote, for example remove the subtraction of the old vote, and see which cases change colour.
</p>
</section>
</div>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How is the score calculated in a voting system?
2. What values can userVote have?
These are 2 of 8 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Vote buttons component
- Click in order
Build the score calculation by clicking the tokens in order:
- Vertical ordering
Order the Claude Code steps for the applyVote function as in the lesson:
- Code editor
Sort posts by mode
- Horizontal ordering
Arrange the line that sets the new vote in applyVote (one line, left to right):
- Horizontal ordering
Arrange the command from CLAUDE.md that runs the tests once, without watch mode (one line, left to right):
- Click in order
Build the expression giving a negative score (50 upvotes, 60 downvotes):
Tasks after this lesson
- QuestionQuiz: Score calculation
- QuestionQuiz: userVote state
- QuestionQuiz: Score result 100 vs 20
- Coding taskPractice: Vote buttons
- Click in orderSequence: Calculate score
- QuestionQuiz: Toggle upvote
- Put in orderSorting: Test first, code second
- QuestionQuiz: The hot formula
- QuestionQuiz: Upvote percentage
- Coding taskPractice: Sorting posts
- Put in orderSorting: The new vote in applyVote
- QuestionQuiz: Hot and the age of a post
- QuestionQuiz: The top and new modes
- Put in orderSorting: The test command
- Click in orderSequence: Negative score