|
| 1 | +import { Buffer } from "node:buffer"; |
| 2 | +import { describe, expect, test } from "vitest"; |
| 3 | +import { truncateCloseReason } from "./close-reason.js"; |
| 4 | + |
| 5 | +describe("truncateCloseReason", () => { |
| 6 | + const multibyte = "\u{1f600}"; |
| 7 | + |
| 8 | + test("returns the fallback for an empty reason", () => { |
| 9 | + expect(truncateCloseReason("")).toBe("invalid handshake"); |
| 10 | + }); |
| 11 | + |
| 12 | + test("keeps close reasons that are already within the byte limit", () => { |
| 13 | + expect(truncateCloseReason("invalid connect params")).toBe("invalid connect params"); |
| 14 | + }); |
| 15 | + |
| 16 | + test("keeps a complete multibyte character when it fits at the byte limit", () => { |
| 17 | + const reason = `${"x".repeat(116)}${multibyte} trailing text`; |
| 18 | + const truncated = truncateCloseReason(reason); |
| 19 | + |
| 20 | + expect(truncated).toBe(`${"x".repeat(116)}${multibyte}`); |
| 21 | + expect(Buffer.byteLength(truncated)).toBe(120); |
| 22 | + }); |
| 23 | + |
| 24 | + test("backs up before a split multibyte character", () => { |
| 25 | + const reason = `${"x".repeat(118)}${multibyte} trailing text`; |
| 26 | + const truncated = truncateCloseReason(reason); |
| 27 | + |
| 28 | + expect(truncated).toBe("x".repeat(118)); |
| 29 | + expect(Buffer.byteLength(truncated)).toBeLessThanOrEqual(120); |
| 30 | + expect(truncated).not.toContain("\uFFFD"); |
| 31 | + }); |
| 32 | + |
| 33 | + test("returns an empty reason when the byte limit cannot fit one character", () => { |
| 34 | + expect(truncateCloseReason(multibyte, 3)).toBe(""); |
| 35 | + }); |
| 36 | +}); |
0 commit comments