I'm trying to mock tRPC procedures so I don't need to run the tRPC backend application to run frontend unit tests. I've tried to use vitest-mock-extended
's mock
and mockDeep
functions. The trpc client still tries to make a request over the network, and get's a connection refused error. vitest-mock-extended
has worked for the trpc backend application.
Works with normal classes
// When userService doesn't use tRPC, it's easy to mock.
const userService = mock<UserService>();
// Works. Typescript suggests all the test functions
userService.createUser.mockResolvedValueOnce({"name": "Fake test user"});
Doesn't work with tRPC procedures
// When using tRPC, typescript doesn't find mockResolvedValueOnce
const userService = mock<typeof context.services.trpcClient.userService>();
// Doesn't work. only `query` or `mutation` is shown.
userService.createUser.mutation.mockResolvedValueOnce({"name": "Fake test user"});
userService.getUser.query.mockResolvedValueOnce({"name": "Fake test user"});
I'm using tRPC, typescript, vitest and vitest-mock-extended.
mockDeep attempt example
const userService = mockDeep<typeof context.services.trpcClient.userService>>();
missionManager.createUser.mutation.mockResolvedValueOnce({...});
missionManager.createUser.query.mockResolvedValueOnce({...});
Has anyone successfully mocked trpc requests on the client side for e.g. a react/typescript application. Since tests are run by vitest, this is actually a Node/jsdom environment.