Created
September 20, 2023 10:41
-
-
Save adicuco/d2e920935844237bf2278a4ff233c038 to your computer and use it in GitHub Desktop.
remix loader/action wrapper for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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