Skip to content

Instantly share code, notes, and snippets.

@adicuco
Created September 20, 2023 10:41
Show Gist options
  • Save adicuco/d2e920935844237bf2278a4ff233c038 to your computer and use it in GitHub Desktop.
Save adicuco/d2e920935844237bf2278a4ff233c038 to your computer and use it in GitHub Desktop.
remix loader/action wrapper for testing
import type { ActionArgs, LoaderArgs } from "@vercel/remix";
import type { Params } from "@remix-run/react";
type Handler<T> = ((args: LoaderArgs) => T) | ((args: ActionArgs) => T);
type TesterArgs = {
path?: string;
body?: Record<string, string>;
headers?: HeadersInit;
params?: Params;
};
export async function tester<T>(
handler: Handler<T>,
{ path = "", body, headers, params }: TesterArgs
) {
const request = new Request(`http://pos.kanpla.dk/${path}`, {
method: handler.name === "loader" ? "GET" : "POST",
...(handler.name === "action" && { body: new URLSearchParams(body) }),
headers,
});
// try-catch needed in order to catch Response objects (thrown redirects)
try {
const res = await handler({
request,
params: params ?? {},
context: {},
});
return res;
} catch (e) {
if (e instanceof Response) {
return e;
} else {
throw e;
}
}
}
// example usage
const response = await tester(loader, {
headers: cookie,
path: "location",
});
const response = await tester(action, {
body,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment