|
| 1 | +import { describe, expect, test } from "vitest"; |
| 2 | +import { formatPercentage, formatPercentageNumber } from "./formatPercentage"; |
| 3 | + |
| 4 | +describe("formatPercentageNumber", () => { |
| 5 | + test("converts ratio to percentage string", () => { |
| 6 | + expect(formatPercentageNumber(0.5)).toBe("50"); |
| 7 | + }); |
| 8 | + |
| 9 | + test("respects digits option", () => { |
| 10 | + expect(formatPercentageNumber(0.123456, { digits: 2 })).toBe("12.35"); |
| 11 | + }); |
| 12 | + |
| 13 | + test("clamps to -100 at minimum", () => { |
| 14 | + expect(formatPercentageNumber(-0.5)).toBe("-50"); |
| 15 | + expect(formatPercentageNumber(-2)).toBe("-100"); |
| 16 | + }); |
| 17 | + |
| 18 | + test("clamps to 100 at maximum", () => { |
| 19 | + expect(formatPercentageNumber(1.5)).toBe("100"); |
| 20 | + }); |
| 21 | + |
| 22 | + describe("sign", () => { |
| 23 | + test("prefixes positive values with +", () => { |
| 24 | + expect(formatPercentageNumber(0.25, { sign: true })).toBe("+25"); |
| 25 | + }); |
| 26 | + |
| 27 | + test("no prefix for zero", () => { |
| 28 | + expect(formatPercentageNumber(0, { sign: true })).toBe("0"); |
| 29 | + }); |
| 30 | + |
| 31 | + test("negative value shows minus sign from the number", () => { |
| 32 | + expect(formatPercentageNumber(-0.1, { sign: true })).toBe("-10"); |
| 33 | + }); |
| 34 | + |
| 35 | + test("respects digits alongside sign", () => { |
| 36 | + expect(formatPercentageNumber(0.1234, { sign: true, digits: 2 })).toBe( |
| 37 | + "+12.34" |
| 38 | + ); |
| 39 | + }); |
| 40 | + }); |
| 41 | +}); |
| 42 | + |
| 43 | +describe("formatPercentage", () => { |
| 44 | + test("appends % symbol", () => { |
| 45 | + expect(formatPercentage(1)).toBe("100%"); |
| 46 | + expect(formatPercentage(0, { digits: 2 })).toBe("0.00%"); |
| 47 | + }); |
| 48 | + |
| 49 | + describe("sign", () => { |
| 50 | + test("prefixes positive values with +", () => { |
| 51 | + expect(formatPercentage(0.25, { sign: true })).toBe("+25%"); |
| 52 | + }); |
| 53 | + |
| 54 | + test("prefixes negative values with -", () => { |
| 55 | + expect(formatPercentage(-0.25, { sign: true })).toBe("-25%"); |
| 56 | + }); |
| 57 | + |
| 58 | + test("no prefix for zero", () => { |
| 59 | + expect(formatPercentage(0, { sign: true })).toBe("0%"); |
| 60 | + }); |
| 61 | + |
| 62 | + test("respects digits alongside sign", () => { |
| 63 | + expect(formatPercentage(0.1234, { sign: true, digits: 2 })).toBe( |
| 64 | + "+12.34%" |
| 65 | + ); |
| 66 | + }); |
| 67 | + }); |
| 68 | +}); |
0 commit comments