Next.js Discord

Discord Forum

Route.ts testing?

Unanswered
Cynipid gall wasp posted this in #help-forum
Open in Discord
Cynipid gall waspOP
Is it possible to test route handlers with Jest? Anyone have a working example?

17 Replies

Route handlers are just API endpoints
I do like testing them with an E2E tools
but in Jest it's doable too, you can either call the function directly with mocked data
or run your server from Jest and test it
I plan to release a course on testing: https://course.nextjspatterns.com/testing-qa-react-server-components-a-next-js-pattern
I don't have examples yet though
Cynipid gall waspOP
@Eric Burel I opened an issue, am I missing something? The linked repo in the issue is about as barebones as it gets. https://github.com/vercel/next.js/issues/61520
It's a tad weird
you spin up an Express app
usually what we do in this case is that we call the API using the "app" object more directly
sorry I am a bit rusty but basically, you don't to run an actual HTTP request when doing that
you can use stuff like supertest
given your setup, why don't you run the actual Next.js app and then call to fetch?
also you don't mention the issue you face: error message, bug, test not running etc.?
this is how I've setup tests against an Express API lately: https://github.com/Devographics/Monorepo/blob/main/api/src/server.test.ts
Next.js codebase has a setup that runs the next app too but way more complex, you might take a look if you have sme spare time
the alternative is "just" calling your route handler by importing it
you don't need the Express server around it, it doesn't bring much value, given also that route handlers are not Node specific (say you want to test an edge route handler someday)