next.js: Unable to test middleware with Jest
What version of Next.js are you using?
12.0.7
What version of Node.js are you using?
16.13.1
What browser are you using?
Firefox
What operating system are you using?
Pop!_OS
How are you deploying your application?
Vercel
Describe the Bug
When trying to test _middleware.js with Jest, I’m unable to import { NextResponse } from 'next/server' without throwing an error SyntaxError: Unexpected token 'export' because next/server uses export { NextRequest } in line 1.
Expected Behavior
I would like to be able to test my _middleware.js authentication methodology.
To Reproduce
- Create a Next app with the aforementioned versions.
- Create a
_middleware.js - Create a test for it in Jest.
- Try to import
NextResponsefromnext/server. - Run tests.
- Get error.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 3
- Comments: 18 (5 by maintainers)
We aim to ship very soon a Jest runtime that will allow you to test middleware code without doing anything special. Just a heads up that we are working on this!
My solution was create
src/__mocks__/next/server.jswith the following content, that fixed the issue to me@gom3s yeah node doesn’t include fetch and you have to use a polyfill.
Import node-fetch or isomorphic-fetch in your
jest.setup.tsIt works!! thank you @wovalle
final setup that works for me
Yeah I guessed so, but what’s weird is that
transformIgnorePatternsis not being respected bynext/jest. I had to go back to use@swc/jestdirectly since I wanted to test middleware functions.In case someone else is interested:
The real deal is adding
node_modules/nexttotransformIgnorePatterns. Probably it could be optimized by only transforming files undernext/serverbut this is good enough for my use case