maloguertin / msw-trpc

tPRC support for MSW
206 stars 20 forks source link

Support for createTRPCReact (react query) #9

Closed nterraza closed 1 year ago

nterraza commented 1 year ago

Is your feature request related to a problem? Please describe. I have a standalone trpc server (with subscriptions) that I use with React, but msw-trpc doesn't support it yet or there are no examples of how to use it with react-query and createTRPCReact. It would be great to have some examples of how to use it with useQuerywithin a react component: https://trpc.io/docs/react

Describe the solution you'd like I would like to have the ability to use msw-trpc with React and be able to mock subscriptions, mutations and queries.

Describe alternatives you've considered Manually mocking the provider.

maloguertin commented 1 year ago

here's an example if you use react-testing-library.

// /tests/utils/trpc.ts

import { createTRPCMsw } from 'msw-trpc'

import type { AppRouter } from '../../server/router'

const trpc = createTRPCMsw<AppRouter>()

export default trpc
// /test/utils/renderer.tsx

import React from 'react'
import {render} from '@testing-library/react'

import { trpc } from '../../hooks/trpc'

const AllTheProviders = ({children}) => {
  const queryClient = new QueryClient({
    logger: {
      error: () => {},
      warn: () => {},
      log: () => {},
    },
  })

  const trpcClient = trpc.createClient({
    links: [
      httpLink({
        url: `http://${global.API_DOMAIN_HTTP}/trpc`,
      }),
    ],
  })

  return (
   <trpc.Provider client={trpcClient} queryClient={queryClient}>
        {children}
      </TranslationProvider>
    </trpc.Provider>
  )
}

const customRender = (ui, options) =>
  render(ui, {wrapper: AllTheProviders, ...options})

// re-export everything
export * from '@testing-library/react'

// override render method
export {customRender as render}

and that is all you can now use msw-trpc in your test files!

ronsigter commented 1 year ago

@maloguertin Hi! 👋

basing from your example for this:

const trpc = createTRPCMsw<AppRouter>()

how does this work to replicate:

<trpc.Provider client={trpcClient} queryClient={queryClient}>
        {children}
  </TranslationProvider> 
</trpc.Provider>

I'm checking the type of createTRPCMsw and it does not return Provider nor has the ability to instantiate createClient

am I missing something? thanks!