Unit tests of remote functions
Describe the problem
I haven't been able to find a way to write unit tests of remote functions without involving hacks that use SvelteKit internals.
I can import the function in the unit test and try to call it, but I get an error Could not get the request store. This is an internal error. at const { event, state } = get_request_store(); inside some internal SvelteKit code. My code is already mocking getRequestEvent but this isn't so straightforward as its an internal file and may involve some extra internal state.
(See below for my current solution which works but is also not great.)
Describe the proposed solution
I'm not really sure of a proper solution here yet that doesn't make too many assumptions about the user's code. But essentially "some simple way to unit test remote functions".
Actually calling the remote functions in unit tests is useful because it ensures that you're actually testing all the code. While it works to test the functions that the remote functions use, that's fragile.
Alternatives considered
Right now I'm mocking the functions in the $app/server module. But to make this work, I had to update the mock implementations to add the __ member that Kit looks for.
(For those unfamiliar, __ holds SvelteKit-specific metadata for remote functions and if it's missing then SvelteKit complains about exporting something that is not a remote function from a remote.ts file)
vi.mock('$app/server', async (importOriginal) => {
const query = (schemaOrHandler: unknown, arg2: unknown) => {
let handler = (arg2 ?? schemaOrHandler) as { __?: { type: string } };
handler.__ = {
type: 'query',
};
// Could wrap this in a schema check as well for good measure
return handler;
};
return {
...(await importOriginal()),
getRequestEvent: vi.fn(() => mockEvent),
query,
// and command, form, query.batch, etc.
};
});
This actually works, but is obviously not a good general solution because it's relies on SvelteKit internals that may change, and expecting someone new to coding and/or SvelteKit to figure this out is asking a bit much.
Importance
nice to have
Additional Information
No response