From a610a872c24b7c8c9aaf4e065fafe1efbe078c5b Mon Sep 17 00:00:00 2001 From: Volker Schukai <volker.schukai@schukai.com> Date: Tue, 28 Mar 2023 10:26:27 +0200 Subject: [PATCH] fix: invalid input throws TypeError --- application/source/dom/dimension.mjs | 10 +++++++++- development/test/cases/dom/dimension.mjs | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/application/source/dom/dimension.mjs b/application/source/dom/dimension.mjs index d145a44bd..e8fdb5e5e 100644 --- a/application/source/dom/dimension.mjs +++ b/application/source/dom/dimension.mjs @@ -70,11 +70,19 @@ function getDeviceDPI() { * @copyright schukai GmbH * @throws {Error} Unsupported unit * @memberOf Monster.DOM + * @throws {Error} Invalid value format */ function convertToPixels(value, parentElement = document.documentElement, fontSizeElement = document.documentElement) { const regex = /^([\d.]+)(.*)$/; - const [, num, unit] = value.match(regex); + const matchResult = value.match(regex); + + if (!matchResult) { + throw new Error(`Invalid value format: ${value}`); + } + + const [, num, unit] = matchResult; + const number = parseFloat(num); const dpi = getDeviceDPI(); diff --git a/development/test/cases/dom/dimension.mjs b/development/test/cases/dom/dimension.mjs index 02241332b..6cf31dd23 100644 --- a/development/test/cases/dom/dimension.mjs +++ b/development/test/cases/dom/dimension.mjs @@ -61,6 +61,16 @@ describe('dimension', () => { expect(result).to.equal(100); }); + it("should throw an error when the input value has an invalid format", () => { + const invalidValue = "invalid_value"; + + const errorFn = () => { + convertToPixels(invalidValue); + }; + + expect(errorFn).to.throw(Error, `Invalid value format: ${invalidValue}`); + }); + it('should correctly convert em values', () => { const testElement = document.createElement('div'); testElement.style.fontSize = '16px'; -- GitLab