icflorescu / trpc-sveltekit

End-to-end typesafe APIs with tRPC.io for your SvelteKit applications.
https://icflorescu.github.io/trpc-sveltekit
ISC License
768 stars 38 forks source link

How to use trpc directly in playwright testing? #123

Open WhyAsh5114 opened 3 months ago

WhyAsh5114 commented 3 months ago

Describe the bug Unable to use trpc client in playwright tests

To Reproduce Steps to reproduce the behavior:

  1. Setup a sveltekit project with playwright enabled
  2. Create a basic tRPC config with an endpoint
  3. Try to directly call it from playwright

Expected behavior The client should work as it does in Svelte files in the frontend

Additional context I tried various methods to create the client in playwright:

  1. I tried using it without args and it gave me an Calling createTRPCClient() on the server requires passing a valid LoadEvent argument
  2. Maybe I'm supposed to use createCaller() with createContext() like we do in server load functions, but what do we pass to the createContext()?
  3. Creating the client with { url: { origin: page.url() } } also doesn't seem to work and give this error: TRPCClientError: Unexpected token '<', "<!doctype "... is not valid JSON
mass8326 commented 3 months ago

Playwright runs in a node environment, so you are unable to create a browser trpc client with trpc-sveltekit. It is missing the necessary context to know where to send the requests.

https://github.com/icflorescu/trpc-sveltekit/blob/bb3259371ca1d40e8dcdcfe0bb88843965b2a9f0/package/src/client.ts#L64-L80

If you want to test your endpoint, you will need to manually create a client with @trpc/client and pass in where your web server is running.

import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';

const client = createTRPCProxyClient({
  links: [httpBatchLink({ url: "..." })],
});
WhyAsh5114 commented 3 months ago

I tried this too, the method returns a weird string union image