Skip to content

Commit

Permalink
feat: Add location stub utility (#28)
Browse files Browse the repository at this point in the history
* feat: Add `location` stub from prerenderer as a utility

* fix: Setup `globalThis.location` & support class methods

* test: Add tests for locationStub utility
  • Loading branch information
rschristian authored Jul 8, 2024
1 parent 6cfff8b commit 1337db0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/prerender.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ export default function prerender(
vnode: VNode,
options?: PrerenderOptions
): Promise<PrerenderResult>;

export function locationStub(path: string): void;
17 changes: 17 additions & 0 deletions src/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,20 @@ export default async function prerender(vnode, options) {
vnodeHook = null;
}
}

/**
* Update `location` to current URL so routers can use things like `location.pathname`
*
* @param {string} path - current URL path
*/
export function locationStub(path) {
globalThis.location = {};
const u = new URL(path, 'http://localhost');
for (const i in u) {
try {
globalThis.location[i] = /to[A-Z]/.test(i)
? u[i].bind(u)
: String(u[i]);
} catch {}
}
}
36 changes: 36 additions & 0 deletions test/location-stub.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, beforeEach, expect } from '@jest/globals';
import { locationStub } from '../src/prerender.js';

describe('location-stub', () => {
beforeEach(() => {
if (globalThis.location) {
delete globalThis.location;
}
});

it('Contains all Location instance properties', () => {
locationStub('/foo/bar?baz=qux#quux');

[
// 'ancestorOrigins', // Not supported by FireFox and sees little use, but we could add an empty val if it's needed
'hash',
'host',
'hostname',
'href',
'origin',
'pathname',
'port',
'protocol',
'search',
].forEach(key => {
expect(globalThis.location).toHaveProperty(key);
});
});

// Do we need to support `assign`, `reload`, and/or `replace`?
it('Support bound methods', () => {
locationStub('/foo/bar?baz=qux#quux');

expect(globalThis.location.toString()).toBe('http://localhost/foo/bar?baz=qux#quux');
});
});

0 comments on commit 1337db0

Please sign in to comment.