Skip to content

Commit

Permalink
fix: href property issue in gatsby build (#580)
Browse files Browse the repository at this point in the history
* fix: href property issue in gatsby build

* chore: improve code coverage
  • Loading branch information
Syed-Ali-Abbas-Zaidi authored Oct 13, 2023
1 parent a5917c2 commit 17876b8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {};
}

/**
Expand All @@ -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 : '';
}

/**
Expand Down
16 changes: 16 additions & 0 deletions src/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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', () => {
Expand Down

0 comments on commit 17876b8

Please sign in to comment.