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

feat: Add location stub utility #28

Merged
merged 3 commits into from
Jul 8, 2024
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
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');
});
});