Skip to content

Commit e9c4ff0

Browse files
committed
backend(tests): add more tests and isHexColor function
1 parent 2a66bae commit e9c4ff0

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

src/utils/validator.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { formatHexColor } from "./hex-color";
77
* @param {string | undefined} width The width.
88
* @returns {number} The parsed width.
99
*/
10-
export const parseWidth = (width = "495"): number => {
10+
export const parseWidth = (width: string | undefined = "495"): number => {
1111
if (width === "495") {
1212
return 495;
1313
}
@@ -21,6 +21,18 @@ export const parseWidth = (width = "495"): number => {
2121
return num;
2222
};
2323

24+
/**
25+
* Function to determine if a string is a valid hexadecimal color.
26+
* Starts with #, 3 or 6 characters long, contains only hexadecimal values
27+
*
28+
* @param {string} color The color string.
29+
* @returns {boolean} True if the color is valid.
30+
*/
31+
export const isHexColor = (color: string): boolean => {
32+
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
33+
return hexColorRegex.test(color);
34+
};
35+
2436
/**
2537
* Converts the line into a Badge array.
2638
* If there's any error in the line,

test/validator.test.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { describe, expect, it } from "vitest";
2+
import { parseWidth, isHexColor } from "../src/utils/validator";
3+
4+
describe("Width parser", () => {
5+
it("should return 495 because the number is not valid", () => {
6+
expect(parseWidth("hi")).toEqual(495);
7+
});
8+
9+
it("should return 495", () => {
10+
expect(parseWidth("495")).toEqual(495);
11+
});
12+
13+
it("should return 495", () => {
14+
expect(parseWidth()).toEqual(495);
15+
});
16+
17+
it("should return 123", () => {
18+
expect(parseWidth("123")).toEqual(123);
19+
});
20+
21+
it("should return 643", () => {
22+
expect(parseWidth("643")).toEqual(643);
23+
});
24+
});
25+
26+
describe("Hex color validator", () => {
27+
it("should return true", () => {
28+
expect(isHexColor("#fff")).toEqual(true);
29+
});
30+
31+
it("should return true", () => {
32+
expect(isHexColor("#fffaaa")).toEqual(true);
33+
});
34+
35+
it("should return true", () => {
36+
expect(isHexColor("#000fff")).toEqual(true);
37+
});
38+
39+
it("should return false", () => {
40+
expect(isHexColor("#ffff")).toEqual(false);
41+
});
42+
43+
it("should return false", () => {
44+
expect(isHexColor("#fffff")).toEqual(false);
45+
});
46+
47+
it("should return false", () => {
48+
expect(isHexColor("ffffff")).toEqual(false);
49+
});
50+
});

0 commit comments

Comments
 (0)