Project: To-Do App with JavaScript, DOM and localStorage (with Tests)
Time to put the course together in a real project. You will build a to-do app for a QA team: add tasks, mark them done, filter, delete, and keep everything after a reload. It uses almost everything from the earlier modules: the DOM, events and delegation, form validation, localStorage and JSON, array methods, immutable updates and pure functions. Then you will test it the way a professional would, with fast unit tests for the logic and Playwright end-to-end tests for the real user flows. All code on this page was run: the app in real Chrome, the unit tests with Node.js, and the Playwright suite against the same files.
📖 What You’ll Learn: how to plan a small app from requirements, writing semantic and accessible HTML, keeping state in one place, separating pure logic from DOM code, rendering a list safely with textContent, handling submit, click and filter events with delegation, validating input, saving and loading with localStorage, unit-testing the logic with node:test, and end-to-end testing with Playwright, plus ideas to extend the project.
📋 Requirements and Plan
Every project starts with requirements, written so that each one can be tested:
| # | Requirement | Tested by |
|---|---|---|
| R1 | A user can add a task with a title (1–80 characters, extra spaces removed) | Unit + E2E |
| R2 | Empty and duplicate titles (case-insensitive) are rejected with a message | Unit + E2E |
| R3 | A task can be marked done and un-done; done tasks are struck through | E2E |
| R4 | Filters show All, Active or Done tasks | Unit + E2E |
| R5 | A task can be deleted; “Clear completed” removes all done tasks | E2E |
| R6 | A counter shows how many tasks are left (“1 task left”, “2 tasks left”) | E2E |
| R7 | Tasks survive a page reload | E2E |
| R8 | Task titles are shown as text, never executed as HTML (no XSS) | E2E |
- State: one array of
{ id, title, done }objects plus the current filter. - Logic: pure functions that take the array and return a new one (
addTask,toggleTask,removeTask,visible). - View: a
render()function that rebuilds the list from the state. - Events: update the state, save it, render again.
🧱 Step 1: The HTML and CSS
Use real form elements, labels and buttons. This gives keyboard support and accessibility for free, and it is exactly what Playwright’s getByLabel and getByRole locators rely on:
📄 index.html (body)
<main class="todo">
<h1>My QA Tasks</h1>
<form id="new-task">
<label for="title">New task</label>
<input id="title" name="title" placeholder="e.g. Write login test cases" autocomplete="off">
<button type="submit">Add</button>
</form>
<p id="error" role="alert"></p>
<nav class="filters" aria-label="Filter tasks">
<button type="button" data-filter="all" aria-pressed="true">All</button>
<button type="button" data-filter="active" aria-pressed="false">Active</button>
<button type="button" data-filter="done" aria-pressed="false">Done</button>
</nav>
<ul id="list"></ul>
<p id="counter" aria-live="polite"></p>
<button type="button" id="clear-done">Clear completed</button>
</main>
📄 style.css
.todo { max-width: 480px; margin: 24px auto; font-family: system-ui, sans-serif; }
#list { list-style: none; padding: 0; }
#list li { display: flex; gap: 8px; align-items: center; padding: 6px 0; border-bottom: 1px solid #eee; }
#list li.done span { text-decoration: line-through; color: #888; }
#list li button { margin-left: auto; }
#error { color: #b91c1c; min-height: 1.2em; }
.filters button[aria-pressed="true"] { font-weight: bold; }
💡 Tip: role="alert" makes screen readers announce errors immediately, and aria-live="polite" announces the counter after changes. aria-pressed tells assistive technology which filter is active.
⚙️ Step 2: The JavaScript
The whole app is about 100 lines, organised in four parts: state, pure logic, rendering and events.
📄 app.js
// ---------- state ----------
const STORAGE_KEY = "qa-todos";
let tasks = load();
let filter = "all";
function load() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) ?? [];
} catch {
return []; // corrupted data: start fresh
}
}
function save() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
}
// ---------- pure logic (easy to unit test) ----------
function addTask(list, title) {
const clean = title.trim().replace(/\s+/g, " ");
if (!clean) throw new Error("Task cannot be empty");
if (clean.length > 80) throw new Error("Task must be 80 characters or less");
if (list.some((t) => t.title.toLowerCase() === clean.toLowerCase())) throw new Error("Task already exists");
return [...list, { id: crypto.randomUUID(), title: clean, done: false }];
}
const toggleTask = (list, id) => list.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
const removeTask = (list, id) => list.filter((t) => t.id !== id);
const visible = (list, f) => list.filter((t) => (f === "active" ? !t.done : f === "done" ? t.done : true));
// ---------- rendering ----------
const listEl = document.querySelector("#list");
const errorEl = document.querySelector("#error");
function render() {
listEl.replaceChildren(
...visible(tasks, filter).map((task) => {
const li = document.createElement("li");
li.dataset.id = task.id;
li.classList.toggle("done", task.done);
const box = document.createElement("input");
box.type = "checkbox";
box.checked = task.done;
box.setAttribute("aria-label", `Complete ${task.title}`);
const span = document.createElement("span");
span.textContent = task.title; // textContent: user text is never parsed as HTML
const del = document.createElement("button");
del.type = "button";
del.className = "delete";
del.textContent = "Delete";
del.setAttribute("aria-label", `Delete ${task.title}`);
li.append(box, span, del);
return li;
})
);
const left = tasks.filter((t) => !t.done).length;
document.querySelector("#counter").textContent = `${left} task${left === 1 ? "" : "s"} left`;
document.querySelectorAll("[data-filter]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === filter)));
}
// ---------- events ----------
document.querySelector("#new-task").addEventListener("submit", (e) => {
e.preventDefault();
const input = e.currentTarget.title;
try {
tasks = addTask(tasks, input.value);
errorEl.textContent = "";
input.value = "";
save();
render();
} catch (err) {
errorEl.textContent = err.message;
}
});
listEl.addEventListener("click", (e) => { // event delegation for every row
const li = e.target.closest("li");
if (!li) return;
const id = li.dataset.id;
if (e.target.matches("input[type=checkbox]")) tasks = toggleTask(tasks, id);
else if (e.target.matches(".delete")) tasks = removeTask(tasks, id);
else return;
save();
render();
});
document.querySelector(".filters").addEventListener("click", (e) => {
const button = e.target.closest("[data-filter]");
if (!button) return;
filter = button.dataset.filter;
render();
});
document.querySelector("#clear-done").addEventListener("click", () => {
tasks = tasks.filter((t) => !t.done);
save();
render();
});
render();
- State and storage (Module 12):
load()parses saved JSON and falls back to an empty list if the data is missing or corrupted. - Pure logic (Module 13): each function returns a new array instead of mutating, so it is trivial to test.
- Safe rendering (Module 12): titles go into
textContent, neverinnerHTML, so user input cannot inject HTML. - Event delegation (Module 12): one click listener on the list handles every checkbox and Delete button, including tasks added later.
- Validation (Module 9 and 12):
addTaskthrows descriptive errors that the submit handler shows to the user.
▶️ Step 3: Run It
Here the browser adds three tasks, completes one and filters, exactly like a user. After each step the page’s visible list, counter and error message are printed:
🎭 What the browser did (Playwright steps)
add "Write login test cases", " Review API tests " and "Run smoke suite"
check "Complete Write login test cases"
click "Active"
click "All", then "Clear completed"
// after each step: print the visible list, the counter and the error message
🖥️ Browser console (after: adding 3 tasks / completing one / Active filter / Clear completed)
["[ ] Write login test cases","[ ] Review API tests","[ ] Run smoke suite"] | 3 tasks left | no error
["[x] Write login test cases","[ ] Review API tests","[ ] Run smoke suite"] | 2 tasks left | no error
["[ ] Review API tests","[ ] Run smoke suite"] | 2 tasks left | no error
["[ ] Review API tests","[ ] Run smoke suite"] | 2 tasks left | no error
Notice that ” Review API tests ” was saved as “Review API tests”: the extra spaces were cleaned. Now the error paths and persistence: an empty title, a duplicate in different case, and a reload:
🎭 What the browser did (Playwright steps)
click "Add" with an empty title
add "Smoke test", then "SMOKE TEST"
add a title of 81 characters
reload the page
// after each step: print the visible list, the counter and the error message
🖥️ Browser console (after: empty title / duplicate / 81 characters / page reload)
[] | 0 tasks left | Task cannot be empty
["[ ] Smoke test"] | 1 task left | Task already exists
["[ ] Smoke test"] | 1 task left | Task must be 80 characters or less
["[ ] Smoke test"] | 1 task left | no error
🧪 Step 4: Unit Tests for the Logic
Because the logic is made of pure functions, it can be tested in Node.js without a browser, in milliseconds (Module 14). The functions below are the same ones as in app.js, exported from their own module:
📄 package.json
{ "type": "module" }
📄 todo-logic.js
export function addTask(list, title) {
const clean = title.trim().replace(/\s+/g, " ");
if (!clean) throw new Error("Task cannot be empty");
if (clean.length > 80) throw new Error("Task must be 80 characters or less");
if (list.some((t) => t.title.toLowerCase() === clean.toLowerCase())) throw new Error("Task already exists");
return [...list, { id: crypto.randomUUID(), title: clean, done: false }];
}
export const toggleTask = (list, id) => list.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
export const removeTask = (list, id) => list.filter((t) => t.id !== id);
export const visible = (list, f) => list.filter((t) => (f === "active" ? !t.done : f === "done" ? t.done : true));
📄 todo-logic.test.js
import { describe, it } from "node:test";
import assert from "node:assert/strict";
import { addTask, toggleTask, removeTask, visible } from "./todo-logic.js";
describe("addTask", () => {
it("adds a trimmed task that is not done", () => {
const [task] = addTask([], " Write tests ");
assert.equal(task.title, "Write tests");
assert.equal(task.done, false);
});
it("rejects empty, too long and duplicate titles", () => {
assert.throws(() => addTask([], " "), /cannot be empty/);
assert.throws(() => addTask([], "x".repeat(81)), /80 characters/);
const list = addTask([], "Smoke test");
assert.throws(() => addTask(list, "SMOKE TEST"), /already exists/);
});
it("accepts exactly 80 characters", () => {
assert.equal(addTask([], "x".repeat(80)).length, 1);
});
it("does not change the original list", () => {
const original = [];
addTask(original, "New");
assert.deepEqual(original, []);
});
});
describe("toggle, remove and filter", () => {
const list = [{ id: "a", title: "A", done: false }, { id: "b", title: "B", done: true }];
it("toggles one task", () => assert.equal(toggleTask(list, "a")[0].done, true));
it("removes one task", () => assert.deepEqual(removeTask(list, "a").map((t) => t.id), ["b"]));
it("filters active and done", () => {
assert.deepEqual(visible(list, "active").map((t) => t.id), ["a"]);
assert.deepEqual(visible(list, "done").map((t) => t.id), ["b"]);
assert.equal(visible(list, "all").length, 2);
});
});
⌨️ Terminal
node --test todo-logic.test.js
🖥️ Output
▶ addTask
✔ adds a trimmed task that is not done (7.7356ms)
✔ rejects empty, too long and duplicate titles (0.8489ms)
✔ accepts exactly 80 characters (0.1877ms)
✔ does not change the original list (0.708ms)
✔ addTask (10.9622ms)
▶ toggle, remove and filter
✔ toggles one task (0.308ms)
✔ removes one task (0.3101ms)
✔ filters active and done (0.2364ms)
✔ toggle, remove and filter (1.1823ms)
ℹ tests 7
ℹ suites 2
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 141.8788
💡 Tip: In a real project, put the pure functions in todo-logic.js and import them into app.js with <script type="module">, so the app and the tests share one copy of the code.
🎭 Step 5: End-to-End Tests with Playwright
Unit tests cannot see the page. These Playwright tests drive the real app in Chrome and cover requirements R1–R8, using the label and role locators the HTML was designed for (setup as in the previous lesson):
📄 tests/todo.spec.js
import { test, expect } from "@playwright/test";
test.beforeEach(async ({ page }) => {
await page.goto("/todo/");
});
async function addTask(page, title) {
await page.getByLabel("New task").fill(title);
await page.getByRole("button", { name: "Add" }).click();
}
test("adds tasks and counts what is left", async ({ page }) => {
await addTask(page, "Write login test cases");
await addTask(page, "Review API tests");
await expect(page.getByRole("listitem")).toHaveText([/Write login test cases/, /Review API tests/]);
await expect(page.locator("#counter")).toHaveText("2 tasks left");
});
test("rejects empty and duplicate tasks", async ({ page }) => {
await addTask(page, " ");
await expect(page.getByRole("alert")).toHaveText("Task cannot be empty");
await addTask(page, "Smoke test");
await addTask(page, "smoke TEST");
await expect(page.getByRole("alert")).toHaveText("Task already exists");
await expect(page.getByRole("listitem")).toHaveCount(1);
});
test("completes, filters and deletes tasks", async ({ page }) => {
await addTask(page, "Task A");
await addTask(page, "Task B");
await page.getByLabel("Complete Task A").check();
await expect(page.locator("#counter")).toHaveText("1 task left");
await page.getByRole("button", { name: "Done" }).click();
await expect(page.getByRole("listitem")).toHaveText([/Task A/]);
await page.getByRole("button", { name: "Active" }).click();
await expect(page.getByRole("listitem")).toHaveText([/Task B/]);
await page.getByRole("button", { name: "All" }).click();
await page.getByRole("button", { name: "Delete Task B" }).click();
await expect(page.getByRole("listitem")).toHaveCount(1);
});
test("keeps tasks after a reload (localStorage)", async ({ page }) => {
await addTask(page, "Persisted task");
await page.reload();
await expect(page.getByRole("listitem")).toHaveText([/Persisted task/]);
const stored = await page.evaluate(() => JSON.parse(localStorage.getItem("qa-todos")));
expect(stored).toHaveLength(1);
expect(stored[0]).toMatchObject({ title: "Persisted task", done: false });
});
test("shows user text as text, not HTML", async ({ page }) => {
await addTask(page, "<img src=x onerror=alert(1)>");
await expect(page.getByRole("listitem")).toContainText("<img src=x onerror=alert(1)>");
await expect(page.locator("#list img")).toHaveCount(0);
});
⌨️ Terminal
npx playwright test tests/todo.spec.js
🖥️ Output (Windows terminal)
Running 5 tests using 1 worker
ok 1 tests\todo.spec.js:12:1 › adds tasks and counts what is left (739ms)
ok 2 tests\todo.spec.js:19:1 › rejects empty and duplicate tasks (557ms)
ok 3 tests\todo.spec.js:28:1 › completes, filters and deletes tasks (753ms)
ok 4 tests\todo.spec.js:44:1 › keeps tasks after a reload (localStorage) (496ms)
ok 5 tests\todo.spec.js:53:1 › shows user text as text, not HTML (459ms)
5 passed (6.5s)
- Each test gets a fresh browser context, so localStorage starts empty and tests cannot affect each other.
- The XSS test enters an
<img onerror>payload and checks that it appears as text and that no image element was created. - The reload test also reads localStorage with
page.evaluateto check the stored data, combining UI and state checks.
🚀 Extend the Project
Ideas to practise further, each with something worth testing:
| Feature | What to test |
|---|---|
| Edit a task by double-clicking it | Enter saves, Escape cancels, empty edit is rejected |
Due dates with <input type="date"> | Overdue tasks highlighted; time-zone boundaries (Module 13) |
| Drag and drop to reorder | Order is saved; Playwright dragTo() |
| Sync with a REST API using fetch | Mock the API with page.route(); offline errors |
| Keyboard shortcuts (N for new task) | Shortcuts do not fire while typing in the input |
Dark mode with prefers-color-scheme | page.emulateMedia({ colorScheme: "dark" }) |
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Add a “Mark all as done” feature to the pure logic: completeAll(list) returns a new list with every task done. Test it.
Show answer
📄 package.json
{ "type": "module" }
📄 practice1.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
const completeAll = (list) => list.map((t) => ({ ...t, done: true }));
test("completeAll", () => {
const list = [{ id: "a", done: false }, { id: "b", done: true }];
const result = completeAll(list);
assert.deepEqual(result.map((t) => t.done), [true, true]);
assert.equal(list[0].done, false, "original list unchanged");
});🖥️ Output
✔ completeAll (1.6172ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 171.2054Q2. Why does the app use span.textContent = task.title instead of building the row with innerHTML and a template string?
Show answer
With innerHTML, a title such as <img src=x onerror=alert(1)> would become real HTML and run script (XSS). textContent always treats the value as plain text. The fifth Playwright test checks exactly this.
Q3. What happens if localStorage contains invalid JSON for “qa-todos”? Which line handles it?
Show answer
JSON.parse throws, the catch in load() returns an empty array, and the app starts with no tasks instead of crashing. A good extra test: set an invalid value with page.addInitScript before loading the page and check that the app still works.
Q4. Write a Playwright step that checks the counter says “0 tasks left” after completing the only task.
Show answer
await page.getByLabel("New task").fill("Only task");
await page.getByRole("button", { name: "Add" }).click();
await page.getByLabel("Complete Only task").check();
await expect(page.locator("#counter")).toHaveText("0 tasks left");Q5. Write stats(list) that returns { total, done, percentDone } (rounded to a whole number, 0 for an empty list).
Show answer
📄 practice5.js
const stats = (list) => {
const done = list.filter((t) => t.done).length;
return { total: list.length, done, percentDone: list.length ? Math.round((done / list.length) * 100) : 0 };
};
console.log(stats([]), stats([{ done: true }, { done: false }, { done: false }]));🖥️ Output
{ total: 0, done: 0, percentDone: 0 } { total: 3, done: 1, percentDone: 33 }Q6. List three manual exploratory checks you would still do on this app after automation passes.
Show answer
Keyboard-only use (Tab, Space, Enter) and screen-reader announcements; behaviour with many tasks (hundreds) and very long words that do not wrap; two tabs open at once (a change in one is not reflected in the other until reload, which could be a product question); and the look on mobile widths.
🧠 MCQ Quiz: Project: To-Do App
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Where does the app keep its data between page loads?Answer: localStorage under the key “qa-todos”. Saved as a JSON string.
- Why are addTask, toggleTask and removeTask written as pure functions?Answer: They are easy to unit test and never mutate state by accident. Same input, same output, new arrays.
- How does one click listener handle every Delete button?Answer: Event delegation with e.target.closest(“li”). It also works for tasks added later.
- Why is task text set with textContent?Answer: To prevent HTML injection (XSS). User text must never be parsed as HTML.
- What does the app do with ” Review API tests “?Answer: Saves “Review API tests”. trim() and collapsing spaces.
- Which requirement is checked by reloading the page in a test?Answer: Tasks survive a reload. R7: persistence.
- Why does each Playwright test start with an empty list?Answer: Each test gets a fresh browser context with its own storage. Isolation is built in.
- Which locator does the test use to complete “Task A”?Answer: getByLabel(“Complete Task A”). The aria-label makes it accessible and stable.
- What protects the app from corrupted saved data?Answer: try…catch around JSON.parse in load(). It falls back to an empty list.
- Which tests are fastest for checking the duplicate rule with many inputs?Answer: Unit tests of addTask. No browser needed.
💼 Interview Questions and Answers
Q1. How would you structure a small front-end app so that it is easy to test?
Keep state in one place, put business rules in pure functions that take data and return new data, isolate side effects (DOM rendering, storage, network) in thin layers, and use semantic, accessible HTML. Then unit tests cover the rules quickly, and a few end-to-end tests cover the real user flows using role and label locators.
Q2. Which risks would you test in a to-do app beyond the happy path?
Validation (empty, whitespace, maximum length, duplicates in different case), XSS through task titles, persistence and corrupted storage, filter and counter correctness after every operation, event delegation for newly added rows, multiple tabs, keyboard accessibility, very large lists, and mobile layout.
Q3. Unit test or end-to-end test: how do you decide where a check belongs?
Rules with many input combinations (validation, calculations, filtering) belong in unit tests: fast and precise. Behaviour that depends on the browser, the DOM, storage, events, rendering or integration between parts belongs in end-to-end tests. Avoid repeating every unit case in the UI; cover each user flow once end-to-end.
Q4. How do you test that data survives a reload in Playwright?
Perform the action, call page.reload(), then assert on the UI with web-first assertions. Optionally read the stored value with page.evaluate(() => localStorage.getItem(key)) and check its structure. To test loading existing or corrupted data, seed storage with page.addInitScript before navigation.
❓ Frequently Asked Questions
🤔 Do I need a framework like React for this project?
No. Plain JavaScript is ideal for learning how the DOM, events and state work. Frameworks automate the render step, and the same testing ideas apply to them.
🤔 How do I run the app locally?
Put index.html, style.css and app.js in one folder (link style.css from index.html, or paste it into a style tag) and open index.html with the VS Code Live Server extension. localStorage and crypto.randomUUID need http://localhost or https, not a file:// URL.
🤔 Why crypto.randomUUID() for ids?
It creates unique ids without a counter that could repeat after a reload, and it is built into modern browsers in secure contexts (https or localhost).
🤔 Can I put this project in my portfolio?
Yes. Publish the code on GitHub with the unit and Playwright tests and a GitHub Actions workflow that runs them; that shows both development and testing skills.
🏁 Summary
- Write testable requirements first, then plan state, pure logic, rendering and events.
- Use semantic, accessible HTML; it also gives Playwright stable label and role locators.
- Keep rules in pure functions, render safely with textContent, and use event delegation.
- Persist with localStorage and JSON, with a safe fallback for missing or corrupted data.
- Unit-test the logic with node:test and cover user flows, persistence and XSS with Playwright.
Next, continue with Lesson 73: Project: Node.js CLI.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in