feat: add jest and initial tests for masking values

This commit is contained in:
Michael Zetterberg
2024-06-19 09:30:06 +02:00
committed by Christel Westerberg
parent d84efcbb0f
commit d28cbf10c7
9 changed files with 3462 additions and 62 deletions

View File

@@ -1,15 +1,44 @@
const emailRegex =
/(?<=.)[^@\n](?=[^@\n]*?@)|(?:(?<=@.+)|(?!^)\G(?=[^@\n]*$)).(?=.*\.)/gm
function maskAllButFirstChar(str: string) {
const first = str[0]
const rest = str.substring(1)
const restMasked = "*".repeat(rest.length)
return `${first}${restMasked}`
}
function maskAllButLastTwoChar(str: string) {
const lastTwo = str.slice(-2)
const rest = str.substring(0, str.length - 2)
const restMasked = "*".repeat(rest.length)
return `${restMasked}${lastTwo}`
}
export function email(str: string) {
return str.replace(emailRegex, "*")
const parts = str.split("@")
const aliasMasked = maskAllButFirstChar(parts[0])
if (parts[1]) {
const domainParts = parts[1].split(".")
if (domainParts.length > 1) {
const domainTLD = domainParts.pop()
const domainPartsMasked = domainParts
.map((domainPart, i) => {
return maskAllButFirstChar(domainPart)
})
.join(".")
return `${aliasMasked}@${domainPartsMasked}.${domainTLD}`
}
}
return maskAllButFirstChar(str)
}
const phoneRegex = /.(?!.{0,1}$)/gm
export function phone(str: string) {
return str.replace(phoneRegex, "*")
return maskAllButLastTwoChar(str)
}
const textRegex = /(?!^)./gm
export function text(str: string) {
return str.replace(textRegex, "*")
return maskAllButFirstChar(str)
}

22
utils/maskvalue.test.ts Normal file
View File

@@ -0,0 +1,22 @@
import { describe, expect, test } from "@jest/globals"
import { email, phone, text } from "./maskValue"
describe("Mask value", () => {
test("masks e-mails properly", () => {
expect(email("test@example.com")).toBe("t***@e******.com")
expect(email("test@sub.example.com")).toBe("t***@s**.e******.com")
expect(email("test_no_atexample.com")).toBe("t********************")
expect(email("test_no_dot@examplecom")).toBe("t*********************")
expect(email("test_no_at_no_dot_com")).toBe("t********************")
})
test("masks phone number properly", () => {
expect(phone("0000000000")).toBe("********00")
})
test("masks text strings properly", () => {
expect(text("test")).toBe("t***")
expect(text("test.with.dot")).toBe("t************")
})
})