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

Added tests for SSR with inferno-router and fix bug in <Switch> #1657

Merged
merged 1 commit into from Dec 2, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/inferno-router/__tests__/loaderOnRoute.spec.tsx
Expand Up @@ -679,4 +679,44 @@ describe('Resolve loaders during server side rendering', () => {
const result = await resolveLoaders(loaderEntries);
expect(result).toEqual(initialData);
});


it('Can resolve with sub classed Route', async () => {
class MyRoute extends Route {
constructor(props, context) {
super(props, context);
}
}
const TEXT = 'bubblegum';
const Component = (props) => {
const res = useLoaderData(props);
return <h1>{res?.message}</h1>;
};

const loaderFuncNoHit = async () => {
return { message: 'no' };
};
const loaderFunc = async () => {
return { message: TEXT };
};

const initialData = {
'/flowers': { res: await loaderFunc() },
'/flowers/birds': { res: await loaderFunc() }
};

const app = (
<StaticRouter context={{}} location="/flowers/birds">
<MyRoute path="/flowers" render={Component} loader={loaderFunc}>
<MyRoute path="/flowers/birds" render={Component} loader={loaderFunc} />
<MyRoute path="/flowers/bees" render={Component} loader={loaderFuncNoHit} />
{null}
</MyRoute>
</StaticRouter>
);

const loaderEntries = traverseLoaders('/flowers/birds', app);
const result = await resolveLoaders(loaderEntries);
expect(result).toEqual(initialData);
});
});
101 changes: 100 additions & 1 deletion packages/inferno-router/__tests__/loaderWithSwitch.spec.tsx
@@ -1,5 +1,5 @@
import { render, rerender } from 'inferno';
import { MemoryRouter, Route, Switch, NavLink, useLoaderData, useLoaderError } from 'inferno-router';
import { MemoryRouter, StaticRouter, Route, Switch, NavLink, useLoaderData, useLoaderError, resolveLoaders, traverseLoaders } from 'inferno-router';
// Cherry picked relative import so we don't get node-stuff from inferno-server in browser test
import { createEventGuard } from './testUtils';

Expand Down Expand Up @@ -364,3 +364,102 @@ describe('A <Route> with loader in a MemoryRouter', () => {
expect(container.querySelector('#publish')).toBeNull();
});
});

describe('Resolve loaders during server side rendering', () => {
it('Can resolve with single route', async () => {
const TEXT = 'bubblegum';
const Component = (props) => {
const res = useLoaderData(props);
return <h1>{res?.message}</h1>;
};

const loaderFunc = async () => {
return { message: TEXT };
};

const initialData = {
'/flowers': { res: await loaderFunc() }
};

const app = (
<StaticRouter context={{}} location="/flowers">
<Switch>
<Route path="/flowers" render={Component} loader={loaderFunc} />
</Switch>
</StaticRouter>
);

const loaderEntries = traverseLoaders('/flowers', app);
const result = await resolveLoaders(loaderEntries);
expect(result).toEqual(initialData);
});

it('Can resolve with multiple routes', async () => {
const TEXT = 'bubblegum';
const Component = (props) => {
const res = useLoaderData(props);
return <h1>{res?.message}</h1>;
};

const loaderFuncNoHit = async () => {
return { message: 'no' };
};
const loaderFunc = async () => {
return { message: TEXT };
};

const initialData = {
'/birds': { res: await loaderFunc() }
};

const app = (
<StaticRouter context={{}} location="/birds">
<Switch>
<Route path="/flowers" render={Component} loader={loaderFuncNoHit} />
<Route path="/birds" render={Component} loader={loaderFunc} />
<Route path="/birds" render={Component} loader={loaderFuncNoHit} />
</Switch>
</StaticRouter>
);

const loaderEntries = traverseLoaders('/birds', app);
const result = await resolveLoaders(loaderEntries);
expect(result).toEqual(initialData);
});

it('Can resolve with nested routes', async () => {
const TEXT = 'bubblegum';
const Component = (props) => {
const res = useLoaderData(props);
return <h1>{res?.message}</h1>;
};

const loaderFuncNoHit = async () => {
return { message: 'no' };
};
const loaderFunc = async () => {
return { message: TEXT };
};

const initialData = {
'/flowers': { res: await loaderFunc() },
'/flowers/birds': { res: await loaderFunc() }
};

const app = (
<StaticRouter context={{}} location="/flowers/birds">
<Route path="/flowers" render={Component} loader={loaderFunc}>
<Switch>
<Route path="/flowers/birds" render={Component} loader={loaderFunc} />
<Route path="/flowers/bees" render={Component} loader={loaderFuncNoHit} />
{null}
</Switch>
</Route>
</StaticRouter>
);

const loaderEntries = traverseLoaders('/flowers/birds', app);
const result = await resolveLoaders(loaderEntries);
expect(result).toEqual(initialData);
});
});
38 changes: 25 additions & 13 deletions packages/inferno-router/src/resolveLoaders.ts
Expand Up @@ -2,6 +2,7 @@ import { isNullOrUndef, isUndefined } from 'inferno-shared';
import { matchPath } from './matchPath';
import type { TLoaderData, TLoaderProps } from './Router';
import { Switch } from './Switch';
import { Route } from './Route';

export function resolveLoaders(loaderEntries: TLoaderEntry[]): Promise<Record<string, TLoaderData>> {
const promises = loaderEntries.map(({ path, params, request, loader }) => {
Expand All @@ -24,8 +25,21 @@ export function traverseLoaders(location: string, tree: any, base?: string): TLo
return _traverseLoaders(location, tree, base, false);
}

function _isSwitch(node: any): boolean {
// Using the same patterns as for _isRoute, but I don't have a test where
// I pass a Switch via an array, but it is better to be consistent.
return node?.type?.prototype instanceof Switch || node?.type === Switch;
}

function _isRoute(node: any): boolean {
// So the === check is needed if routes are passed in an array,
// the instanceof test if routes are passed as children to a Component
// This feels inconsistent, but at least it works.
return node?.type?.prototype instanceof Route || node?.type === Route;
}

// Optionally pass base param during SSR to get fully qualified request URI passed to loader in request param
function _traverseLoaders(location: string, tree: any, base?: string, parentIsSwitch = false): TLoaderEntry[] {
function _traverseLoaders(location: string, tree: any, base?: string, parentIsSwitch = false): TLoaderEntry[] {
// Make sure tree isn't null
if (isNullOrUndef(tree)) return [];

Expand All @@ -34,7 +48,7 @@ function _traverseLoaders(location: string, tree: any, base?: string, parentIsSw
const entriesOfArr = tree.reduce((res, node) => {
if (parentIsSwitch && hasMatch) return res;

const outpArr = _traverseLoaders(location, node, base, node?.type?.prototype instanceof Switch);
const outpArr = _traverseLoaders(location, node, base, _isSwitch(node));
if (parentIsSwitch && outpArr.length > 0) {
hasMatch = true;
}
Expand All @@ -44,9 +58,7 @@ function _traverseLoaders(location: string, tree: any, base?: string, parentIsSw
}

const outp: TLoaderEntry[] = [];
let isRouteButNotMatch = false;
if (tree.props) {
// TODO: If we traverse a switch, only the first match should be returned
if (_isRoute(tree) && tree.props) {
// TODO: Should we check if we are in Router? It is defensive and could save a bit of time, but is it worth it?
const { path, exact = false, strict = false, sensitive = false } = tree.props;
const match = matchPath(location, {
Expand All @@ -57,10 +69,10 @@ function _traverseLoaders(location: string, tree: any, base?: string, parentIsSw
});

// So we can bail out of recursion it this was a Route which didn't match
isRouteButNotMatch = !match;

// Add any loader on this node (but only on the VNode)
if (match && !tree.context && tree.props?.loader && tree.props?.path) {
if (!match) {
return outp;
} else if (!tree.context && tree.props?.loader && tree.props?.path) {
// Add any loader on this node (but only on the VNode)
const { params } = match;
const controller = new AbortController();
const request = createClientSideRequest(location, controller.signal, base);
Expand All @@ -75,11 +87,11 @@ function _traverseLoaders(location: string, tree: any, base?: string, parentIsSw
}
}

// Traverse ends here
if (isRouteButNotMatch) return outp;

// Traverse children
const entries = _traverseLoaders(location, tree.children || tree.props?.children, base, tree.type?.prototype instanceof Switch);
const children = tree.children ?? tree.props?.children;
if (isNullOrUndef(children)) return outp;

const entries = _traverseLoaders(location, children, base, _isSwitch(tree));
return [...outp, ...entries];
}

Expand Down