-
Hey Team, I have dynamic API routes in my application. I tried following approach for testing API routes and it works well with routes which don't deal with
Please help! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
Got it. We can use
|
Beta Was this translation helpful? Give feedback.
-
I keep seeing it written this way: server = http.createServer((req, res) => apiResolver(req, res, undefined, handler)); But it does not match what is expected:
It's expecting a export declare function apiResolver(
req: IncomingMessage,
res: ServerResponse,
params: any,
resolverModule: any,
apiContext: __ApiPreviewProps,
onError?: ({ err }: { |
Beta Was this translation helpful? Give feedback.
-
The simplest solution I found was to use
|
Beta Was this translation helpful? Give feedback.
-
After recycling route testing code from project to project for a while, I wrapped it up in a convenient package: next-test-api-route-handler. Maybe it'll be useful! import * as endpoint from '../pages/api/endpoint'
import { testApiHandler } from 'next-test-api-route-handler'
import type { WithConfig } from '@ergodark/next-types'
// Import the handler under test from the pages/api directory and respect the
// Next.js config object if it's exported
const endpoint: WithConfig<typeof Endpoint.default> = Endpoint.default;
endpoint.config = Endpoint.config;
await testApiHandler({
requestPatcher: req => req.headers = { key: SPECIAL_API_KEY },
handler: endpoint,
test: async ({ fetch }) => {
expect(await fetch({ method: 'GET', body: 'data' })).toStrictEqual({ json: 'response' });
}
}); |
Beta Was this translation helpful? Give feedback.
Got it. We can use
URLSearchParams
with the above approach to achieve it.