Skip to content

Commit 17876b8

Browse files
fix: href property issue in gatsby build (#580)
* fix: href property issue in gatsby build * chore: improve code coverage
1 parent a5917c2 commit 17876b8

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/utils.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,13 @@ export function convertKeyNames(object, nameMap) {
138138
* @returns {Object}
139139
*/
140140
export function parseURL(url) {
141-
const parser = document?.createElement('a');
142-
parser.href = url;
143-
return parser;
141+
if (typeof document !== 'undefined') {
142+
const parser = document.createElement('a');
143+
parser.href = url;
144+
return parser;
145+
}
146+
147+
return {};
144148
}
145149

146150
/**
@@ -151,7 +155,7 @@ export function parseURL(url) {
151155
* @returns {string}
152156
*/
153157
export function getPath(url) {
154-
return parseURL(url).pathname;
158+
return typeof document !== 'undefined' ? parseURL(url)?.pathname : '';
155159
}
156160

157161
/**

src/utils.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ describe('getQueryParameters', () => {
119119
describe('ParseURL', () => {
120120
const testURL = 'http://example.com:3000/pathname/?search=test#hash';
121121
const parsedURL = parseURL(testURL);
122+
let originalDocument;
123+
124+
beforeEach(() => {
125+
originalDocument = global.document;
126+
});
127+
128+
afterEach(() => {
129+
global.document = originalDocument;
130+
});
131+
122132
it('String URL is correctly parsed', () => {
123133
expect(parsedURL.toString()).toEqual(testURL);
124134
expect(parsedURL.href).toEqual(testURL);
@@ -152,6 +162,12 @@ describe('ParseURL', () => {
152162
it('should return host from URL', () => {
153163
expect(parsedURL.host).toEqual('example.com:3000');
154164
});
165+
166+
it('should return empty object in case of document being undefined', () => {
167+
delete global.document;
168+
169+
expect(parseURL(testURL)).toEqual({});
170+
});
155171
});
156172

157173
describe('getPath', () => {

0 commit comments

Comments
 (0)