Mugetsu
Mugetsu2w ago

How to get a TRPCClientError shape as in initTRPC errorFormatter for testing

I want to test some UI logic handling errors from trpc but I struggle how to setup the error shape in the test so it triggers proper branches while test. here is my initTrpc
const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
errorFormatter({ error, shape }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
apiError: ApiError.isApiError(error.cause) ? error.cause.errors : [],
errorStatuses: [
shape.data.httpStatus,
ApiError.isApiError(error.cause) ? error.cause.status : undefined,
],
},
};
},
});
const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
errorFormatter({ error, shape }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
apiError: ApiError.isApiError(error.cause) ? error.cause.errors : [],
errorStatuses: [
shape.data.httpStatus,
ApiError.isApiError(error.cause) ? error.cause.status : undefined,
],
},
};
},
});
Handler I want to test:
export const onFormApiError = (error: unknown) => {
if (!isTRPCClientError(error)) return; // should never trigger

// HOW DO I SETUP THE ERROR IN TEST WITH THIS SHAPE
const errors = error?.data?.apiError || [];
....
}
export const onFormApiError = (error: unknown) => {
if (!isTRPCClientError(error)) return; // should never trigger

// HOW DO I SETUP THE ERROR IN TEST WITH THIS SHAPE
const errors = error?.data?.apiError || [];
....
}
And How can I test it???
it('test test', () => {
// WHAT DO I PASS HERE AS PROPER ERRROR with the shape??
onFormApiError(new TRPCClientError('test3', { data: { apiError: [] } }));

});
it('test test', () => {
// WHAT DO I PASS HERE AS PROPER ERRROR with the shape??
onFormApiError(new TRPCClientError('test3', { data: { apiError: [] } }));

});
Solution:
OK nvm. Just found implementation of trpclienterror and you can do ``` new TRPCClientError('test3', { result: { error: { data: { apiError: [] } } },...
Jump to solution
1 Reply
Solution
Mugetsu
Mugetsu2w ago
OK nvm. Just found implementation of trpclienterror and you can do
new TRPCClientError('test3', {
result: { error: { data: { apiError: [] } } },
}),
new TRPCClientError('test3', {
result: { error: { data: { apiError: [] } } },
}),