Design Tests for a Text Truncation or Snippet Function That Catch Split Characters and Unit Mismatches

You are designing unit tests for a function that shortens text for display: a snippet generator, a "truncate to N characters with an ellipsis" helper, a title shortener for notifications, or a preview of a chat message.

I will give you the function's signature, its stated contract (the maximum length and whether it counts bytes, UTF-16 code units, code points or user-perceived characters), and the code if I have it. Produce a table-driven test plan that covers:

1. Length boundaries: input exactly at the limit, one below, one above, empty string, and a limit smaller than the ellipsis itself.
2. Unit mismatch: which unit the limit is measured in versus which unit the code actually counts. Include a case where the two differ, such as an emoji or accented letter that is one visible character but several code units or bytes.
3. Never splitting a character: a surrogate pair, a combining accent (e + U+0301), a flag emoji built from two regional indicators, and a family emoji joined with zero-width joiners, each placed so the cut lands inside it.
4. Word boundaries, if the contract promises them: a single word longer than the limit, trailing whitespace before the ellipsis, and text with no spaces at all (Chinese or Japanese, URLs).
5. Markup and escaping: input containing HTML entities, Markdown, or an already-escaped string, where cutting mid-entity (`&am…`) would produce broken output.
6. Right-to-left and mixed-direction text, checking where the ellipsis lands.
7. Idempotence: truncating an already-truncated string should not change it again.

For each case give: input (write invisible characters as escapes like ‍), limit, expected output, and the bug it catches. State any assumption about the contract you had to make. If the contract does not say which unit it counts, put that first as a question, because the expected outputs depend on it.

---

When to use it: when writing or reviewing any text-shortening helper, especially one whose output goes into fixed-width UI, push notifications, SMS or database columns with byte limits.

How to adapt it: if the limit is a storage constraint (for example a byte-limited column), make bytes the unit and add cases at multi-byte boundaries. If you only render in one language, still keep the emoji cases; users paste emoji everywhere.

Example input: `truncate(s: string, max: number): string`, documented as "at most max characters including the trailing …", implemented with `s.slice(0, max - 1) + '…'` in JavaScript.

Good output points out that `slice` counts UTF-16 code units, so a cut in the middle of 👍 leaves a lone surrogate. It gives that exact case with its expected result, and asks whether "characters" means graphemes. Weak output lists "test long strings" and "test empty strings" and stops.

Sign in to upvote this prompt.