This file provides utilities for mocking tRPC routes in a Cypress testing environment. It is designed to simplify mocking and testing of tRPC APIs by integrating seamlessly with Cypress. It is a fork of cy-trpc but has support for tRPC v11, returning parial objects, and waiting for procedures to execute.
The utility includes:
- Stubbing tRPC procedures: Simulate API responses with
returns
andreturnsPartial
. - Intercepting requests: Modify API responses dynamically with
intercept
. - Waiting for requests: Wait for specific API calls with
wait
.
The main export is the stubTRPC
function, which generates a proxy for stubbing and interacting with tRPC routes.
Copy trpc-stub into your repository
Add it to your Cypress globals
import { stubTRPC } from './trpc-stub';
const trpcStub = stubTRPC<AppRouter>();
cy.api = trpcStub;
declare global {
namespace Cypress {
interface Chainable {
api: typeof trpcStub;
}
}
}
Disable link batching while in Cypress
links: [
typeof window !== 'undefined' && window.Cypress
? httpLink({
transformer: SuperJSON,
url: getBaseUrl() + '/api/trpc',
headers: () => {
const headers = new Headers();
headers.set('x-trpc-source', 'nextjs-react');
return headers;
},
})
: unstable_httpBatchStreamLink({
transformer: SuperJSON,
url: getBaseUrl() + '/api/trpc',
headers: () => {
const headers = new Headers();
headers.set('x-trpc-source', 'nextjs-react');
return headers;
},
}),
],
// Stub a procedure
trpcMock.myProcedure.returns({ key: 'value' });
// Intercept and transform a procedure's response
trpcMock.myProcedure.intercept((value) => ({
...value,
extraKey: 'extraValue',
}));
// Wait for a procedure call
trpcMock.myProcedure.wait();
Stub a tRPC procedure to return a specific response.
trpcMock.someProcedure.returns({ key: 'value' });
Stub a tRPC procedure to return a partial response.
trpcMock.someProcedure.returnsPartial({ key: 'partialValue' });
Intercept a tRPC procedure and dynamically transform the response.
trpcMock.someProcedure.intercept((value) => ({ ...value, newKey: 'newValue' }));
Wait for the mocked tRPC procedure to be called.
trpcMock.someProcedure.wait();
Access the full path of the tRPC procedure.
console.log(trpcMock.someProcedure.path); // Outputs: 'someProcedure'
The utility can be extended to include additional Cypress methods or custom logic. Simply modify the CypressTRPCMock
type or stubTRPC
implementation as needed.
- The utility relies on Cypress's
cy.intercept
for mocking and request handling. - Ensure your
tRPC
router and procedure types are properly defined for type safety. - Default transformers are applied, but custom transformers can be provided via
StubOptions
. - This will not have 100% coverage of Cypress or tRPC, you are meant to add functionality as you need it