Skip to main content
Frontend tutorial

6.1. Write the first test

Let's start with CounterStore. The scenarios we want to test are already in /Store.test.ts as test.todo. Replace the first one with this test:

test('new counter', () => {
const counter = new CounterStore();
expect(counter.value).toBe(1);
});

Choose Run tests. It fails: we expected 1, but received 0. A new counter starts at 0, so this time the test is wrong, not the store. Change 1 to 0 and run it again. It's worth seeing every new test fail once; a test that can't fail doesn't check anything.

Now the check you did by hand in chapter 4. Replace the next test.todo:

test('add to a typed value', () => {
const counter = new CounterStore();
counter.setValue('42');
counter.add(1);
expect(counter.value).toBe(43);
});

Every test has the same three parts: arrange (create the store), act (call its actions) and assert (check the result with expect).

Need a hint?
  • Read the failure: it shows what you expected and what the store gave.
  • Each test creates its own CounterStore, so tests never share a value.

Run the tests again. Both pass, and the rest of the list is still waiting.

Work locally

Download this step’s starting code (.zip) and extract it. Open a terminal in the folder with package.json. With Node.js 24 and pnpm installed, run the tests:

pnpm install --frozen-lockfile
pnpm test:run

Run pnpm dev to open the chapter 4 counter app.

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./06-01-first-test-my-files.json
pnpm test:run

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…