Web Development courseLesson 18 of 20 · tap to see all lessons
Web Development · Beginner
Testing, Debugging, and Responsible AI-Assisted Development for Web Applications
Debug with DevTools and server logs, test forms, APIs, and CRUD by hand and with Node's test runner, check usability and responsiveness, and use AI tools responsibly.
- Qyubie Learn Editorial Team
- Published
- 16 min read
Includes 1 exercise and 2 quick checks you can do right here.
Your class portal now has pages, an API, a database, and logins. Every one of those parts can break, and some of them will. This lesson is about finding problems before your users do: debugging (finding out why something is wrong), testing (proving that it works, and keeps working), checking that the app is usable on every screen, and using AI tools in a way that makes you faster without making your app worse.
By the end of this lesson you will be able to:
- use the browser's DevTools and the server's terminal to find bugs,
- follow a step-by-step debugging process,
- write a test plan for forms, APIs, and CRUD, and automate tests with Node's test runner,
- check usability, responsiveness, and accessibility, and
- use AI coding tools responsibly: verifying, protecting data, and owning your code.
Where errors show up
A Next.js app runs in two places, so its messages appear in two places:
| Code that runs in... | Shows console.log and errors in... |
|---|---|
the browser (client components, "use client" files) | the browser's DevTools Console |
the server (server components, Server Actions, Route Handlers, proxy.ts) | the terminal where npm run dev is running |
Beginners often add console.log to a Server Action and look for it in the browser. It's in the terminal.
Browser DevTools
Press F12 (or right-click the page → Inspect) to open DevTools. The panels you'll use most:
| Panel | Use it to |
|---|---|
| Elements | see the real HTML and CSS of the page, edit styles live, find out why a style doesn't apply |
| Console | read errors and console.log output, and run JavaScript on the page |
| Network | see every request: URL, method, status code, request body, and response |
| Application | look at cookies (like the sb-...-auth-token session cookie), localStorage, and storage |
| Sources | set breakpoints and step through code line by line |
Three habits that solve most front-end bugs:
- Read the whole error message, including the file and line number.
TypeError: Cannot read properties of undefined (reading 'map')means something you called.mapon wasundefined, usually data that hasn't loaded or came back in a different shape. - Check the Network panel for any feature that loads or saves data. Click the request: is the status
200,401,404,422, or500? What did the Response tab say? Half of "my page doesn't work" is a request that failed. - Throttle the network. The Network panel can simulate a slow connection or go offline. That's the easiest way to see your loading and error states (lesson 15) actually work.
The device toolbar (the phone icon in DevTools) shows the page at phone sizes. Check every page at about 390 pixels wide.
A debugging process
Guessing and changing random lines wastes hours. Work like a scientist:
- Reproduce it. Find the exact steps that make the bug happen every time.
- Read the evidence: error messages, the Network panel, the terminal.
- Narrow it down. Is the data wrong when it leaves the database, when the server sends it, or when the component shows it? Check each step with
console.logor a breakpoint. - Form a hypothesis ("the year arrives as a string, so
===fails") and test it. - Fix the cause, not the symptom.
- Retest, including the cases that worked before.
Here's a small bug to practice on. The class average should be 85, but this prints something else. Run it, then look at the extra console.log line, which shows the problem:
Try it · JavaScript
Output:
total is 0908085 of type string
average: 3026950 + "90" doesn't add; it joins text, giving "090", then "09080", and so on. Form values, URL parameters, and FormData are always strings. The fix is to convert them: total += Number(g);. That's exactly why validateStudent in lesson 15 uses Number(raw.year).
Exercise · JavaScript
Fix the average
This function should return the average of the scores, rounded to 1 decimal place, but it has two bugs. Find and fix them so the program prints Average: 86.7 and Average: 0.
Expected output
Average: 86.7 Average: 0
Hint
The loop starts at 1, so it skips the first score. And an empty list divides 0 by 0, which is NaN: return 0 early when scores.length is 0.
Show a solution
Try it yourself first — you learn more from a wrong attempt than from reading an answer.
function average(scores) {
if (scores.length === 0) return 0;
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
return Number((total / scores.length).toFixed(1));
}
console.log("Average:", average([90, 85, 85]));
console.log("Average:", average([]));
Testing forms, APIs, and CRUD
A test plan
Before you call a feature done, write down what you'll check, then check it. A test plan lists each case, what you do, and what should happen. For the "Add student" form:
| # | Case | Steps | Expected result |
|---|---|---|---|
| 1 | valid student | fill every field correctly, submit | redirected to the list; new student shown |
| 2 | empty form | submit with nothing filled in | an error next to every field; nothing saved |
| 3 | bad year | year 7 | "Year must be 1 to 4."; other fields keep their values |
| 4 | duplicate number | use an existing student number | "You already have a student with that number." |
| 5 | not logged in | log out, open /students/new | redirected to the login page |
| 6 | another user's data | log in as a second account | the first account's students aren't listed |
| 7 | slow network | throttle to a slow connection, submit | button shows "Saving..." and can't be clicked twice |
| 8 | phone | 390 px wide | fields fit; no sideways scrolling |
Notice how few rows are the "happy path". Most bugs live in the other cases: empty, invalid, duplicate, unauthorized, slow, and small screens. For CRUD, add cases for edit (the form is pre-filled, changes save), delete (the row disappears, and only that row), and a missing ID (/students/99999/edit shows "not found").
Automated tests with Node's test runner
Clicking through a plan every time you change something gets old fast. Automated tests are code that checks your code. Node.js has a built-in test runner, so you don't need to install anything.
Pure functions like validateStudent are the easiest to test: give an input, check the output. Create a tests folder in your project:
// tests/validate.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { validateStudent } from "../lib/validate.ts";
const good = {
studentNo: "2025-0003",
fullName: "Cara Santos",
course: "BSCS",
year: "1",
email: "Cara@Example.com",
};
test("accepts a valid student and cleans the email", () => {
const result = validateStudent(good);
assert.equal(result.ok, true);
assert.equal(result.data.email, "cara@example.com");
assert.equal(result.data.year, 1);
});
test("rejects a year outside 1 to 4", () => {
const result = validateStudent({ ...good, year: "5" });
assert.equal(result.ok, false);
assert.equal(result.errors.year, "Year must be 1 to 4.");
});
test("rejects a badly formatted student number", () => {
const result = validateStudent({ ...good, studentNo: "25-3" });
assert.deepEqual(Object.keys(result.errors), ["studentNo"]);
});
test("reports every problem at once", () => {
const result = validateStudent({});
assert.deepEqual(Object.keys(result.errors).sort(), ["course", "email", "fullName", "studentNo", "year"]);
});test(name, fn)defines one test;assert.equalandassert.deepEqualfail the test when values differ.- Importing
../lib/validate.tsdirectly works on Node.js 22.18 or newer, which runs TypeScript files by removing the types. (In plain Node, the.tsextension in the import is required.)
Add a script to package.json:
"test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test tests/*.test.mjs"(The --disable-warning part hides a harmless notice that Node prints when it reads validate.ts as a module.) Run npm test:
✔ accepts a valid student and cleans the email (0.8526ms)
✔ rejects a year outside 1 to 4 (0.2538ms)
✔ rejects a badly formatted student number (0.7374ms)
✔ reports every problem at once (0.1927ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0Now suppose someone changes the year rule to data.year > 5 by mistake. The test catches it immediately:
✖ rejects a year outside 1 to 4 (1.0326ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
true !== falseThat's the real value of tests: they guard behavior you already got right, so later changes can't quietly break it.
Testing your API
API tests send real requests to a running app and check the status and body. Start npm run dev in one terminal, then run this file in another:
// tests/api.e2e.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
const BASE = process.env.BASE_URL ?? "http://localhost:3000";
test("GET /api/students returns a list", async () => {
const response = await fetch(`${BASE}/api/students`);
assert.equal(response.status, 200);
assert.ok(Array.isArray(await response.json()));
});
test("POST with invalid data returns 422 and field errors", async () => {
const response = await fetch(`${BASE}/api/students`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fullName: "" }),
});
assert.equal(response.status, 422);
const body = await response.json();
assert.equal(body.errors.fullName, "Enter the full name.");
});
test("POST with text that isn't JSON returns 400", async () => {
const response = await fetch(`${BASE}/api/students`, { method: "POST", body: "hello" });
assert.equal(response.status, 400);
});
test("GET a missing student returns 404", async () => {
const response = await fetch(`${BASE}/api/students/999999`);
assert.equal(response.status, 404);
});"test:api": "node --test tests/api.e2e.mjs"Tests that click through pages in a real browser (logging in, filling forms) are called end-to-end tests; tools such as Playwright do that. They're worth learning once your app grows, and the test plan above is exactly the list they'd automate.
Quick check
Usability, responsiveness, and accessibility
An app can pass every test and still be hard to use. Before calling a page done, check:
Responsive
- At 390 px wide: no sideways scrolling, nothing cut off, buttons big enough to tap (about 44 px tall).
- At laptop size: content isn't stretched too wide to read; forms use the space (side-by-side fields).
- Zoom the browser to 200%: everything still works.
Usable
- Every page has a clear title, and the main action is obvious.
- Loading, empty, and error states all exist and say what to do next.
- Buttons say what they do ("Add student", not "Submit").
- Errors appear next to the field, in plain words, and the user's input is kept.
Accessible (usable by people with disabilities, and better for everyone)
- Every input has a
<label>; images havealttext. - You can use the whole page with the keyboard only: Tab moves through controls in a sensible order, and focus is visible.
- Text has enough contrast against its background.
- Errors use
role="alert"so screen readers announce them.
Chrome DevTools has a Lighthouse panel that audits a page and lists accessibility, performance, and best-practice problems. Treat its report as a starting point, and still test with a keyboard and a real phone.
Using AI tools responsibly
AI coding assistants can explain errors, suggest code, and write tests in seconds. They can also be confidently wrong. Use them like a fast, well-read classmate who sometimes makes things up, and whose work you must check.
What they're good for
- Explaining an error message, a concept, or code you're reading.
- Reviewing your code: "What could go wrong with this Server Action?"
- Generating test cases you hadn't thought of.
- Boilerplate you understand well and can check quickly.
Why you must verify everything
AI tools learn from older code, and web frameworks change fast. In this course alone:
| An AI tool might write | But in the versions this course uses |
|---|---|
a middleware.ts file | Next.js 16 renamed it to proxy.ts |
params.id in a page | params is a Promise: const { id } = await params |
an error.tsx with a reset prop | current Next.js passes retry |
supabase.auth.getSession() to protect a page | use getClaims() on the server |
NEXT_PUBLIC_SUPABASE_ANON_KEY | new projects use the publishable key |
It can also write code that works but isn't safe: a policy with using ( true ) for writes, a secret key in a NEXT_PUBLIC_ variable, or a Server Action that never checks who's calling. So:
- Check the official docs for the version you use (Next.js even ships its docs inside
node_modules/next/dist/docs/). - Run it and test it, including the error cases.
- Read every line before you commit it. If you can't explain a line, you're not ready to submit it.
Protect data and secrets
Whatever you paste into an AI tool leaves your computer. Never paste .env.local contents, API keys, passwords, or real people's personal data (like real student records). Replace them with fake values first.
Honesty and learning
- Follow your instructor's policy on AI use for each activity, and say when and how you used AI if you're asked to.
- You are responsible for the code you submit, whoever or whatever wrote the first draft.
- Don't skip the learning. Try the problem first; use AI to get unstuck or to check your thinking, not to replace it. In a job interview or an exam, the AI won't be there; your understanding will.
A responsible workflow: try → ask → read → run → test → review → commit.
Quick check
Common mistakes
- Looking for server logs in the browser, or browser errors in the terminal.
- Ignoring the Network panel when data doesn't load or save.
- Testing only the happy path.
- Changing several things at once while debugging, so you don't know which one fixed it (or broke something else).
- Never testing on a phone-sized screen or with the keyboard.
- Committing AI-generated code you haven't read, run, and tested.
- Pasting secrets or real personal data into AI tools.
Summary
- Client code logs to the DevTools Console; server code logs to the terminal. The Network panel shows every request's status and response.
- Debug by reproducing, reading the evidence, narrowing down, testing a hypothesis, fixing the cause, and retesting.
- Write test plans that cover invalid, duplicate, unauthorized, slow, and small-screen cases. Automate checks with
node:test: unit tests for functions, API tests against a running app. - Check responsiveness (390 px, 200% zoom), usability (clear states and messages), and accessibility (labels, keyboard, contrast, Lighthouse).
- Use AI to explain, review, and suggest, then verify against current docs, test, protect secrets and personal data, follow the course policy, and own every line you submit.
Next: GitHub workflow and deployment, where the class portal goes live on the internet.