T
tRPC

Mocking tRPC call w/ Playwright (Transform Error)

Mocking tRPC call w/ Playwright (Transform Error)

MTMatt Thompson4/26/2023
I have a tRPC call that I would like to mock out for a Playwright E2E test. I've followed their docs as shown below and used the same transformer (superjson) from our tRPC setup.
When inspected via network tab the Call seems to succeed as expected. (image) However, the client errors w/
TRPCClientError: Unable to transform response from server
at transformResult (transformResult-6fb67924.mjs:74:1)
at eval (httpBatchLink.mjs:188:56)
TRPCClientError: Unable to transform response from server
at transformResult (transformResult-6fb67924.mjs:74:1)
at eval (httpBatchLink.mjs:188:56)
https://playwright.dev/docs/mock#mock-api-requests
import { transformer } from '@/utils/trpc';
...
await page.route('**/api/trpc/onboarding.verifyPrimaryPractice?batch=1', (route) => {
route.fulfill({
status: 200,
body: transformer.stringify({ success: true }),
headers: { 'Content-Type': 'application/json' },
});
});
import { transformer } from '@/utils/trpc';
...
await page.route('**/api/trpc/onboarding.verifyPrimaryPractice?batch=1', (route) => {
route.fulfill({
status: 200,
body: transformer.stringify({ success: true }),
headers: { 'Content-Type': 'application/json' },
});
});
Nnlucas4/26/2023
Are you writing code to interact with the API directly? Maybe best to use the tRPC Client for this? https://trpc.io/docs/client/introduction OH sorry, I see you're intercepting and stubbing it out? Not familiar with playwright We would generally recommend you bring your API under test with tRPC. It's easier to stub out external services and control DB state than to replace the API, and makes for more representative e2e tests If you're really keen on it though, it looks like your approach is on the right track
MTMatt Thompson4/26/2023
Correct, we are using trpc client below on the form submit. I'm trying to stub that call out. Outside of the transform piece - it seems to be working as expected. I'm just unsure why the transform fails.
const verifyPractice = trpc.onboarding.verifyPrimaryPractice.useMutation({
onSuccess: () => {...}
onError: () => {...}
})

...

const handleOnSubmit = async (data) => await verifyPractice.mutateAsync(data);
const verifyPractice = trpc.onboarding.verifyPrimaryPractice.useMutation({
onSuccess: () => {...}
onError: () => {...}
})

...

const handleOnSubmit = async (data) => await verifyPractice.mutateAsync(data);
Nnlucas4/26/2023
You have batching enabled on the client (batch=1), but it looks like your transformed response is in the unbatched response form 2 recommendations: 1. return your response in an array like you'll see when you run your app for real 2. don't match the whole URL, just match the onboarding.verifyPrimaryPractice bit, as a batched up call will have several paths comma separated and an encoded array of inputs to send to each one respectively - shouldn't be too hard to parse the inputs and respond in the correct form Probably will save pain all round if you just disable batching during testing though. I bet responding to a batched request with 2 calls in would be a PITA
MTMatt Thompson4/26/2023
Looking at the above. Do you mind expanding on this a bit? " We would generally recommend you bring your API under test with tRPC.
Nnlucas4/26/2023
Run the API for real Emulate any 3rd party services, run local DBs with real/mock data in.
MTMatt Thompson4/26/2023
Ah, Yea For the most part we are doing that with Factories, etc. This call has a 3rd party call where I don't have a Sandbox to run against. I was originally looking for the equiv of Jest.mock in Playwright E2E The closest thing they support is Network mocking Sadly the 3rd party call couldn't be mocked in this scenario as the tRPC call is calling it within Fun edge case I guess. I'm looking at the real result like you mentioned above and trying to mock the array. I didn't take that into account earlier. 🤞 Worked 🙂 End Result for me:
await page.route('**/api/trpc/onboarding.verifyPrimaryPractice?batch=1', (route) => {
route.fulfill({
status: 200,
body: JSON.stringify([
{ result: { data: { json: { success: true } }, meta: { values: {} } } },
]),
headers: { 'Content-Type': 'application/json' },
});
});
await page.route('**/api/trpc/onboarding.verifyPrimaryPractice?batch=1', (route) => {
route.fulfill({
status: 200,
body: JSON.stringify([
{ result: { data: { json: { success: true } }, meta: { values: {} } } },
]),
headers: { 'Content-Type': 'application/json' },
});
});
In this case I don't really care about the return - I simply want it to keep going But you could mock out the full return under data.json here. The way the tests run, I shouldn't have more than one for batch Thanks for the 👀 and help @Nick Lucas

Looking for more? Join the community!

T
tRPC

Mocking tRPC call w/ Playwright (Transform Error)

Join Server
Recommended Posts
zod input validation from ts typeI imported a type using `import type { WebhookEvent } from "@clerk/nextjs/api";`. Is there a way to Looking to fix my tRPC implementationHi guys I am looking for some help implementing tRPC in my current project, I have 3 files that needExpression produces a union type that is too complex to representHi! I have started to encounter the above on error on pretty simple react components using trpc v10 Skipping useQuery with typescriptI'm wondering if there is a way to skip a query in a typescript friendly way? `rtk-query` has a handClerk Webhook Input UndefinedHi! I wrote a public procedure that takes in an input and updates user info based on Clerk Webhook. Getting this error: Cannot read properties of undefined (reading 'upsert')I'm using the T3 Stack. And I'm fairly new to tRPC so I am not sure what this error is caused. I'm Stuck trying to utilize useQuery to fetch some data on form submissionI'm trying to call a procedure in trpc through the use of useQuery in react upon form submission. SocreateTRPCNext type errorHi everyone. So I started creating nextjs app with trpc + prisma set up. and when i use my AppRouterFull cache invalidation and timing problemI'm really enjoying using the full cache invalidation https://trpc.io/docs/reactjs/usecontext#invaliUsing Next.JS + FastifyMy node environment is Node 18, powered by PNPM. What's wrong: I have a few requirements for my appError Handling vs Error FormattingI'm a bit confused from the docs about how I should be handling errors on the server. The Error HandNext.js body-parsing issueA thead to discuss this issue: https://github.com/trpc/trpc/issues/4243Cannot find module '@trpc/react-query/server' or its corresponding type declarations```ts import { createServerSideHelpers } from '@trpc/react-query/server' ``` This should work, righProcedure with generic input?Is there a way to define a procedure so that it takes input with type parameters, and returns outputDelete item {0: {json:{id: 12324}}}When i try to mutate/delete item with id i am geting this payload `{0: {json:{id: 12324}}}`, withouQuery function depends on a variableIn tRPC v10 accessing a specific path is really easy, but because of that I don't control the query 'useInfiniteQuery' hook disappeared after moving to TurborepoI am using Turborepo with Next.js with the following layout, originally a T3 app - `/apps/app` - `/pconvert the result to date objectsI am not sure if this is even trpcs responsibility but I would like to get my date objects as date oECONNREFUSED with TRPC call on VercelAnyone run into this before? I just deployed my app to Vercel and I run into this error when I triggInvalid ValDoes TRPC string input have a limit? https://prnt.sc/KlXlyoGrzP8P Edit: It was actually from strip