Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 30 ยท Projects

Project: Test a Form Validator

Test a sign-up form validator with Jest: table-driven rules with test.each, a custom matcher for field errors and a snapshot of error messages, with stand-ins.

Form validation is a perfect target for tests. It is pure logic (values in, error messages out), it has many small rules, and a single missed edge case, such as a password of exactly eight characters, becomes a bug users see. In this project you will test a sign-up validator using three techniques from earlier chapters: table-driven tests, a custom matcher and a snapshot of the messages.

Real Jest does not run on this site, so the Jest code is read-only. The runnable examples are honest stand-ins: a loop over a table instead of test.each, a tiny toHaveFieldError check instead of expect.extend, and a stored string instead of a snapshot file. The validator itself is ordinary JavaScript and runs for real.

Three tools, one validator

test.each One row per rule and edge case.
Custom matcher toHaveFieldError reads like a sentence.
Snapshot Lock down the exact wording of messages.

Each tool answers a different question about the same function.

1 / 2

The validator

The validator takes the raw form values and returns { valid, errors }, where errors maps a field name to one message (the first rule that fails).

JavaScript
// validate-signup.js
export function validateSignup(form) {
  const errors = {};
  const username = (form.username ?? "").trim();
  const email = (form.email ?? "").trim();
  const password = form.password ?? "";

  if (username === "") {
    errors.username = "Username is required.";
  } else if (username.length < 3) {
    errors.username = "Username needs at least 3 characters.";
  } else if (!/^[a-z0-9_]+$/i.test(username)) {
    errors.username = "Use only letters, digits and underscores.";
  }

  if (email === "") {
    errors.email = "Email is required.";
  } else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
    errors.email = "Enter a valid email address.";
  }

  if (password.length < 8) {
    errors.password = "Password needs at least 8 characters.";
  } else if (!/\d/.test(password)) {
    errors.password = "Password needs at least one digit.";
  }

  if ((form.confirm ?? "") !== password) {
    errors.confirm = "Passwords do not match.";
  }

  return { valid: Object.keys(errors).length === 0, errors };
}

Because every rule has a boundary, the tests below will concentrate on those boundaries.

Table-driven rules with test.each

A table puts the input and the expected message side by side, which makes gaps visible: if there is no row for an empty string, you can see it. In Jest, test.each takes the rows and a title template (see Table-Driven Tests with test.each):

JavaScript
import { validateSignup } from "./validate-signup.js";

const valid = { username: "ada_l", email: "[email protected]", password: "engine123", confirm: "engine123" };

describe("username rule", () => {
  test.each([
    ["",        "Username is required."],
    ["   ",     "Username is required."],
    ["ab",      "Username needs at least 3 characters."],
    ["abc",     undefined],
    ["a b c",   "Use only letters, digits and underscores."],
    ["ada-l",   "Use only letters, digits and underscores."],
  ])("username %j gives %j", (username, message) => {
    const { errors } = validateSignup({ ...valid, username });
    expect(errors.username).toBe(message);
  });
});

Every row spreads the known-good form and changes one field. That keeps each test about a single rule, and any failure points to exactly one row. Rows such as " " and "abc" are boundaries: the first checks that trimming happens, the second that three characters is allowed.

A custom matcher for field errors

Asserting result.errors.email over and over is noisy. A custom matcher states the intent directly. With expect.extend (see Errors and Custom Matchers):

JavaScript
expect.extend({
  toHaveFieldError(result, field, message) {
    const actual = result.errors[field];
    const pass = actual === message;
    return {
      pass,
      message: () =>
        pass
          ? `expected ${field} not to have the error ${this.utils.printExpected(message)}`
          : `expected ${field} error ${this.utils.printExpected(message)}, received ${this.utils.printReceived(actual)}`,
    };
  },
});

test("rejects a short password", () => {
  const result = validateSignup({ ...valid, password: "short1", confirm: "short1" });
  expect(result).toHaveFieldError("password", "Password needs at least 8 characters.");
  expect(result.valid).toBe(false);
});

The failure message is the real value of a custom matcher: it names the field and shows both the expected and received text.

Stand-in 1: the table and the matcher

The stand-in below runs the same table with a for loop and implements toHaveFieldError as a plain function that throws with a clear message, which is how matchers behave inside.

Node.js Stand-in: table rows and a field-error matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The password rows sit on both sides of the boundary: "abcdef1" has 7 characters and fails the length rule, while "abcdefg1" has exactly 8 and passes. The last line of output shows the failure message the matcher produces when an expectation is wrong. Remember that a table row is a claim about the code: when it fails, decide whether the row or the code is wrong.

Snapshot the messages

Do you need to assert the wording of every message? Usually the important thing is that the right fields fail, but a snapshot is a cheap way to lock the whole error object for one hard case. Use an empty form, because it triggers the most rules at once:

JavaScript
test("an empty form reports every field", () => {
  const { errors } = validateSignup({});
  expect(errors).toMatchInlineSnapshot();
});

Jest fills in the argument for you the first time the test runs: a template string listing email, password and username with their messages (Jest sorts object keys in snapshots). Check each snapshot by eye before committing it: it records whatever the code does, correct or not. See Snapshot Testing for when snapshots help and when they only add noise.

The stand-in shows the mechanism with a stored string: the first run would write it, later runs compare.

Node.js Stand-in: a stored snapshot of the error messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The empty form matches the stored text. An input that adds the confirm error produces a different object, so the comparison is false; a real Jest run would print a diff and fail until you review the change and update the snapshot.

What each tool is for

  • Table (test.each) for rules and boundaries: many inputs, one assertion.
  • Custom matcher for repeated, domain-specific checks with clear failure text.
  • Snapshot for a few large outputs whose exact shape you want to freeze, never for every rule.

Do not snapshot the whole result for each row of a table. Thirty snapshots that nobody reads are accepted blindly with -u, and then they protect nothing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does each table row spread the known-good form and change a single field?

    Changing one field at a time isolates the rule being tested, so unrelated errors cannot confuse the result.
  2. 2. Which input is a boundary case for a rule 'at least 3 characters'?

    Boundary tests sit right on each side of the limit: the shortest accepted value and the longest rejected one.
  3. 3. What is the main benefit of a custom matcher like toHaveFieldError?

    A custom matcher turns a repeated lookup-and-compare into one sentence and lets you write a precise failure message.
  4. 4. When should you avoid a snapshot?

    Snapshots are best for a few big outputs. For small rules, an explicit assertion is clearer and cannot be accepted blindly.

Summary

  • Validators are pure functions, so tests are quick: values in, { valid, errors } out.
  • Use test.each tables with one changed field per row and put rows on both sides of every boundary.
  • A custom matcher such as toHaveFieldError gives readable assertions and helpful failure messages.
  • Snapshot only a few large outputs, review them by eye, and never accept -u blindly.
  • A table row is a claim about the code: when it fails, decide whether the row or the code is wrong.

Next, practice everything on your own in Jest Exercises with Solutions.