Automatic fetch replacement #672
-
Hi! Is there a way to automatically replace I have a page that fetch('/api/backend') with // backend.api.js:
handler(new NextApiRequest(something), new NextApiResponse()) Does this make sense? Would it not be possible with this lib? Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
From what you describe, it sounds like you want to use something like Mock Service Worker (MSW), which is compatible with NTARH. You can use MSW to capture and interrogate fetch #2 while leaving NTARH to optimally handle fetch #1. Rarely, if ever, do you want to directly mock any For example: import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { testApiHandler } from 'next-test-api-route-handler';
import handler from './backend.api.js';
const server = setupServer(
rest.all('url-pattern-matching-the-third-party-service-you-are-talking-about', async (req, res, ctx) => {
// Test fetch #2, which is coming from inside of your handler, here
})
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => {
server.resetHandlers();
});
afterAll(() => server.close());
await testApiHandler({
handler,
test: async ({ fetch }) => {
// This is fetch #1 made to Next.js
const res = await fetch('/api/backend');
// Test fetch #1 (and potentially fetch #2 too) here
await expect(res.json()).resolves.toStrictEqual({ ... });
}
}); For further assistance, reply with a MRE demonstrating your issue :) |
Beta Was this translation helpful? Give feedback.
NextApiRequest
andNextApiResponse
are TypeScript types, not classes. They don't actually exist, so you can't createnew
instances of them. You're actually dealing withIncomingMessage
andServerResponse
instances (respectively) with methods added by the Next.js API resolver. The purpose of NTARH is to pull this resolver out of Next.js's source code and run it for you (i.e. your handlers receive objects satisfying theNextApiRequest
andNextApiResponse
type definitions) just by calling the extremely convenienttestApiHandler
function.From what you describe, it sounds like you want to use something like Mock Service Worker (MSW), which is compatible with NTARH. You can use MSW to capture …