Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: href property issue in gatsby build #580

Merged
merged 2 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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