A tiny string highlighter that keeps my tests from being flaky

Yo Kirupa folks, I’m wiring up some UI tests right now and I keep losing time on failures where the diff is basically “one extra space” or a line wrap that shifts, so I started using a little text formatter to make assertions more stable.

export function normalizeForAssert(input, {
  max = 120,
  highlight = "",
} = {}) {
  const text = String(input)
    .replace(/\r\n?/g, "\n")
    .replace(/[\t\f\v]+/g, " ")
    .replace(/\u00A0/g, " ")
    .replace(/[ \u200B]+/g, " ")
    .replace(/\s+\n/g, "\n")
    .trim();

  const truncated = text.length > max ? text.slice(0, max - 1) + "…" : text;

  if (!highlight) return truncated;

  const safe = highlight.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return truncated.replace(new RegExp(safe, "gi"), (m) => `⟦${m}⟧`);
}

Neat part is it makes the “real” content pop while smoothing out wrapping/whitespace noise, so failures feel deterministic instead of random when fonts or layout shift a bit.

the regex escaping bit is the one that bites people. [ or ( in a highlight string will absolutely ruin your day if you don’t neutralize it first.

one thing i’d be wary of: truncating before the highlight pass can chop the match out entirely, so the failure looks tidy but the word you cared about never shows up. i’ve had that sort of thing make a test look “stable” when it was just hiding the useful part of the diff.