TripleSpeeder
TripleSpeeder7mo ago

typed useQuery mock

I'm trying to make a quick mock for useQuery. It's basically working, but I would like to have the query typed. This is the current implementation:
export const useQuery = fn((query, ...args) => {
if (args[0] === "skip") {
return undefined;
}
const queryName = getFunctionName(query);
switch (queryName) {
case "manufacturer/queries:getManufacturerQuery":
return manufacturer;
default:
throw new Error(
`Unexpected query call ${queryName}! Please add a mock :)`,
);
...

export const useQuery = fn((query, ...args) => {
if (args[0] === "skip") {
return undefined;
}
const queryName = getFunctionName(query);
switch (queryName) {
case "manufacturer/queries:getManufacturerQuery":
return manufacturer;
default:
throw new Error(
`Unexpected query call ${queryName}! Please add a mock :)`,
);
...

What are the correct types for query and ...args? I would like the return of getFunctionName to be typed based on my schema/api. Is this possible?
3 Replies
lee
lee7mo ago
I would do
import {useQuery: realUseQuery} from "./_generated/api";
export const useQuery = ((ctx, args) => {...mock impl...}) as any as typeof realUseQuery;
import {useQuery: realUseQuery} from "./_generated/api";
export const useQuery = ((ctx, args) => {...mock impl...}) as any as typeof realUseQuery;
Does that work?
TripleSpeeder
TripleSpeederOP7mo ago
No, i want to have the types inside the actual mock implementation. So e.g. in the switch statement, if i add a case for a not-existing query i get the appropriate typescript error thrown at me. Or if i return a mock response that does not conform the real response type.
sshader
sshader7mo ago
GitHub
convex-helpers/src/fakeConvexClient/fakeConvexClient.d.ts at main ·...
A collection of useful code to complement the official packages. - get-convex/convex-helpers