From 257412c5c7127b1237260dfef75a8caf781f30dc Mon Sep 17 00:00:00 2001 From: Kaung Myat Lwin Date: Sat, 14 Jan 2023 17:56:48 +0700 Subject: [PATCH] fix: proper input validation thrown error --- myanmar-phonenumber.js | 10 +++++----- test/test.js | 11 +++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/myanmar-phonenumber.js b/myanmar-phonenumber.js index df08f91..6b5c320 100644 --- a/myanmar-phonenumber.js +++ b/myanmar-phonenumber.js @@ -43,14 +43,14 @@ // Removes trailing spaces, dashes and double country codes myanmarPhoneNumber.sanitizeInput = function (phoneNumber) { + if (!phoneNumber) { + throw Error('Please include phoneNumber parameter.'); + } + phoneNumber = phoneNumber.trim(); if (phoneNumber.length === 0) { - return new Error('Phone number is empty.'); - } - - if (!phoneNumber) { - return new Error('Please include phoneNumber parameter.'); + throw Error('Phone number is empty.'); } phoneNumber = phoneNumber.replace(/[- )(]/g,'') diff --git a/test/test.js b/test/test.js index 9f42b35..d0d3ba9 100644 --- a/test/test.js +++ b/test/test.js @@ -1,6 +1,17 @@ var assert = require('assert'); var myanmarPhoneNumber = require('../myanmar-phonenumber.js') +describe('Error throwing: ', function() { + it('should throw an error when empty string is passed', () => { + assert.throws(() => myanmarPhoneNumber.sanitizeInput(' '), Error) + assert.throws(() => myanmarPhoneNumber.sanitizeInput(''), Error) + }) + + it('should throw an error when "undefined" is passed', () => { + assert.throws(myanmarPhoneNumber.sanitizeInput, Error) + }) +}); + describe('Normalize input: ', function() { it('should return +959784123456 to 09784123456', function() { assert.equal(myanmarPhoneNumber.normalizeInput('+959784123456'), '09784123456');