Skip to content

Instantly share code, notes, and snippets.

@beck
Last active March 29, 2018 16:16
Show Gist options
  • Save beck/731ca089974b95444794109b133e962e to your computer and use it in GitHub Desktop.
Save beck/731ca089974b95444794109b133e962e to your computer and use it in GitHub Desktop.
urlstr
/*
Why is this needed?
> is `url.format` broken or am I?
> https://github.com/nodejs/help/issues/1176
Would like to:
- extract this as a standalone lib
- support all spaces as options:
https://nodejs.org/api/url.html#url_url_strings_and_url_objects
*/
export default (options) => {
const defaults = {
hostname: (window.location && window.location.hostname) || 'localhost',
};
const { hostname, pathname, query } = { ...defaults, ...options };
const dummyURL = 'https://.';
const url = new window.URL(dummyURL);
url.hostname = hostname;
url.pathname = pathname || url.pathname;
if (query) {
const newSearchParams = new window.URLSearchParams(query);
url.search = newSearchParams;
}
return url.href;
};
import urlstr from './urlstr';
describe('urlstr()', () => {
test('returns "https://localhost/"', () => {
expect(urlstr()).toBe('https://localhost/');
});
describe('called in a browser', () => {
let loc;
beforeEach(() => {
loc = window.location;
delete window.location;
window.location = {
hostname: 'fake-host',
};
});
afterEach(() => {
window.location = loc;
});
test('returns "https://fake-host/"', () => {
expect(urlstr()).toBe('https://fake-host/');
});
});
});
describe('urlstr({ pathname: "/womp.html" }) - using slash', () => {
const expected = 'https://localhost/womp.html';
test(`returns ${expected}`, () => {
const str = urlstr({ pathname: '/womp.html' });
expect(str).toBe(expected);
});
});
describe('urlstr({ pathname: "womp.html" }) - no slash', () => {
const expected = 'https://localhost/womp.html';
test(`returns ${expected}`, () => {
const str = urlstr({ pathname: 'womp.html' });
expect(str).toBe(expected);
});
});
describe('urlstr({ hostname: "homer.doh" })', () => {
const expected = 'https://homer.doh/';
test(`returns ${expected}`, () => {
const str = urlstr({ hostname: 'homer.doh' });
expect(str).toBe(expected);
});
});
describe('urlstr({ query: { a: "aye", b: "bee/ee" }})', () => {
const expected = 'https://localhost/?a=aye&b=bee%2Fee';
test(`returns ${expected}`, () => {
const str = urlstr({ query: { a: 'aye', b: 'bee/ee' } });
expect(str).toBe(expected);
});
});
describe('with a hostname, pathname, and query', () => {
const expected = 'https://homer.doh/womp.html?beer=yes%21';
test(`returns ${expected}`, () => {
const str = urlstr({
hostname: 'homer.doh',
pathname: 'womp.html',
query: { beer: 'yes!' },
});
expect(str).toBe(expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment