Is it possible to reproduce the case where the server side throws a TRPCError?
haga-triple1 opened this issue · 6 comments
Is your feature request related to a problem? Please describe.
yes. I would like to reproduce a case where the server side throws a TRPCError in a unit test, but the documentation does not describe how to do this.
Describe the solution you'd like
Documentation of how to resolve the above (and implementation if not already done)
Describe alternatives you've considered
nothing
Additional context
nothing
You could use a conditional:
export const handlers = [
trpcMsw.candidates.all.query((req, res, ctx) => {
// in my case, the request has these search filters, so I'm using one to trigger an error
// {
// '0': {
// filters: { onlyApproved: false, search: '' },
// pageNumber: 1
// }
// }
const { search } = req.getInput()?.["0"].filters;
if (search === "fail")
return res(ctx.status(400), ctx.data(mockErrorResponse));
return res(ctx.status(200), ctx.data(mockResponse));
}),
];
Al least, this will work is you are passing parameters. Because you could decide to fail if the parameter value is ... whatever you decide.
Thank you for your response.
That is not what I intended. I apologize for the lack of explanation.
My question is "What value should I assign to 'mockErrorResponse'?". The tRPC client cannot interpret it as a 400 error. It handles it the same way as if the network connection is not established.
Got it. See:
const mockErrorResponse = {
error: {
message: "Ups",
code: -32603,
data: {
code: "INTERNAL_SERVER_ERROR",
httpStatus: 500,
stack: "Error: Ups",
path: "candidates.all", // Maybe this has to match your request, not sure. I don't think so
},
},
}
Note I'm using ctx.json
and not ctx.data
for the error response:
return res(ctx.status(500), ctx.json(fakeServer.mockErrorResponse));
Thank you! It worked.
I'd like to support a way to emulate this officially if possible, so let's keep it open...
Thank you! It worked. I'd like to support a way to emulate this officially if possible, so let's keep it open...
This seems like a good feature, if you want to take a shot at it you're more than welcome too. Else I'll try to add it to my roadmap :)
Thanks to @libasoles for the example and the clarification about using ctx.json()
instead of ctx.data()
.
I was using superjson as the transformer
, so I had to manually add the json
and meta
wrappers that superjson expects myself.
To show it with code:
Because I had this:
const trpcMsw = createTRPCMsw<AppRouter>({
transformer: { input: superjson, output: superjson },
});
I had to do this in my test (note the json
and meta
keys):
const error = {
error: {
json: {
message: 'test error',
code: -32603,
data: {
code: 'INTERNAL_SERVER_ERROR',
httpStatus: 500,
stack: 'Error: Oops',
path: 'candidates.all',
},
},
meta: [],
}
}
return res(ctx.status(500), ctx.json(error));