colors.spec.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { describe, expect, it } from "vitest";
  2. import { darkenColor, hexToRgb, lightenColor, rgbToHex } from "./colors.js";
  3. //#region hexToRgb
  4. describe("colors/hexToRgb", () => {
  5. it("Converts a hex color string to an RGB tuple", () => {
  6. const hex = "#FF0000";
  7. const [r, g, b, a] = hexToRgb(hex);
  8. expect(r).toBe(255);
  9. expect(g).toBe(0);
  10. expect(b).toBe(0);
  11. expect(a).toBeUndefined();
  12. });
  13. it("Converts a hex color string with an alpha channel to an RGBA tuple", () => {
  14. const hex = "#FF0000FF";
  15. const [r, g, b, a] = hexToRgb(hex);
  16. expect(r).toBe(255);
  17. expect(g).toBe(0);
  18. expect(b).toBe(0);
  19. expect(a).toBe(1);
  20. });
  21. it("Works as expected with invalid input", () => {
  22. expect(hexToRgb("")).toEqual([0, 0, 0, undefined]);
  23. });
  24. });
  25. //#region rgbToHex
  26. describe("colors/rgbToHex", () => {
  27. it("Converts an RGB tuple to a hex color string", () => {
  28. expect(rgbToHex(255, 0, 0, undefined, true, true)).toBe("#FF0000");
  29. expect(rgbToHex(255, 0, 0, undefined, true, false)).toBe("#ff0000");
  30. expect(rgbToHex(255, 0, 0, undefined, false, false)).toBe("ff0000");
  31. expect(rgbToHex(255, 0, 127, 0.5, false, false)).toBe("ff007f80");
  32. expect(rgbToHex(0, 0, 0, 1)).toBe("#000000ff");
  33. });
  34. it("Handles special values as expected", () => {
  35. expect(rgbToHex(NaN, Infinity, -1, 255)).toBe("#nanff00ff");
  36. expect(rgbToHex(256, -1, 256, -1, false, true)).toBe("FF00FF00");
  37. });
  38. it("Works as expected with invalid input", () => {
  39. expect(rgbToHex(0, 0, 0, 0)).toBe("#000000");
  40. //@ts-ignore
  41. expect(rgbToHex(NaN, "ello", 0, -1)).toBe("#nannan0000");
  42. });
  43. });
  44. //#region lightenColor
  45. describe("colors/lightenColor", () => {
  46. it("Lightens a color by a given percentage", () => {
  47. expect(lightenColor("#ab35de", 50)).toBe("#ff50ff");
  48. expect(lightenColor("ab35de", Infinity, true)).toBe("FFFFFF");
  49. expect(lightenColor("rgba(255, 50, 127, 0.5)", 50)).toBe("rgba(255, 75, 190.5, 0.5)");
  50. expect(lightenColor("rgb(255, 50, 127)", 50)).toBe("rgb(255, 75, 190.5)");
  51. });
  52. });
  53. //#region darkenColor
  54. describe("colors/darkenColor", () => {
  55. it("Darkens a color by a given percentage", () => {
  56. // since both functions are the exact same but with a different sign, only one test is needed:
  57. expect(darkenColor("#1affe3", 50)).toBe(lightenColor("#1affe3", -50));
  58. });
  59. });