WeCodeAcademy

Step 8: Test the rules

The URL validation is the security-critical part, so test it thoroughly: good addresses, wrong protocols, protocol-relative links, empty and non-string input. Add a test for normalisation too: HTTPS://EXAMPLE.com becomes https://example.com/, so the same link is recognised however it was typed.

ExampleNode.js
const assert = require("assert");

function parseTarget(input) {
  if (typeof input !== "string" || input.length > 2000) return { error: "bad type or too long" };
  let url;
  try { url = new URL(input); } catch { return { error: "not a valid URL" }; }
  if (url.protocol !== "http:" && url.protocol !== "https:") return { error: "only http and https" };
  return { url: url.toString() };
}

const cases = [
  ["https://example.com", true],
  ["http://example.com/a?b=c#d", true],
  ["ftp://example.com", false],
  ["javascript:alert(1)", false],
  ["//example.com", false],
  ["", false],
  [null, false],
];

let failed = 0;
for (const [input, shouldPass] of cases) {
  try {
    assert.strictEqual(Boolean(parseTarget(input).url), shouldPass);
    console.log("ok  ", JSON.stringify(input));
  } catch {
    failed++;
    console.log("FAIL", JSON.stringify(input));
  }
}
console.log(failed === 0 ? `all ${cases.length} cases passed` : `${failed} failed`);

// a normalised URL is stable, so the same link can be recognised twice
assert.strictEqual(parseTarget("HTTPS://EXAMPLE.com").url, "https://example.com/");
console.log("normalisation ok");
Output
ok   "https://example.com"
ok   "http://example.com/a?b=c#d"
ok   "ftp://example.com"
ok   "javascript:alert(1)"
ok   "//example.com"
ok   ""
ok   null
all 7 cases passed
normalisation ok

You have built the core of a link shortener: random ids, URL validation, redirects, statistics, rate limiting, a database design and tests. Where next: add custom aliases, expiry dates, a QR code, authentication so users own their links, and deploy it behind HTTPS.

Quick check

Which part of the shortener most needs thorough tests?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.