From 17876b8714cca7afdaba33c2463300e2e6d092c8 Mon Sep 17 00:00:00 2001 From: Syed Ali Abbas Zaidi <88369802+Syed-Ali-Abbas-Zaidi@users.noreply.github.com> Date: Fri, 13 Oct 2023 17:29:49 +0500 Subject: [PATCH] fix: href property issue in gatsby build (#580) * fix: href property issue in gatsby build * chore: improve code coverage --- src/utils.js | 12 ++++++++---- src/utils.test.js | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/utils.js b/src/utils.js index debd1b1a7..7d7412839 100644 --- a/src/utils.js +++ b/src/utils.js @@ -138,9 +138,13 @@ export function convertKeyNames(object, nameMap) { * @returns {Object} */ export function parseURL(url) { - const parser = document?.createElement('a'); - parser.href = url; - return parser; + if (typeof document !== 'undefined') { + const parser = document.createElement('a'); + parser.href = url; + return parser; + } + + return {}; } /** @@ -151,7 +155,7 @@ export function parseURL(url) { * @returns {string} */ export function getPath(url) { - return parseURL(url).pathname; + return typeof document !== 'undefined' ? parseURL(url)?.pathname : ''; } /** diff --git a/src/utils.test.js b/src/utils.test.js index cd5e6eac3..6b0723af0 100644 --- a/src/utils.test.js +++ b/src/utils.test.js @@ -119,6 +119,16 @@ describe('getQueryParameters', () => { describe('ParseURL', () => { const testURL = 'http://example.com:3000/pathname/?search=test#hash'; const parsedURL = parseURL(testURL); + let originalDocument; + + beforeEach(() => { + originalDocument = global.document; + }); + + afterEach(() => { + global.document = originalDocument; + }); + it('String URL is correctly parsed', () => { expect(parsedURL.toString()).toEqual(testURL); expect(parsedURL.href).toEqual(testURL); @@ -152,6 +162,12 @@ describe('ParseURL', () => { it('should return host from URL', () => { expect(parsedURL.host).toEqual('example.com:3000'); }); + + it('should return empty object in case of document being undefined', () => { + delete global.document; + + expect(parseURL(testURL)).toEqual({}); + }); }); describe('getPath', () => {