Unable to test middleware with Jest
See original GitHub issueWhat 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
NextResponse
fromnext/server
. - Run tests.
- Get error.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:3
- Comments:18 (4 by maintainers)
Top Results From Across the Web
How to test express middleware error handler with jest and ...
In you handler, you call response.status(status).send(error); , this mean .status() should return an object what include send function, ...
Read more >Unit test Express middleware - TypeScript, Jest
When I write unit tests including any structural items of the Express library, it produces me I have to avoid testing the library...
Read more >Testing | Next.js
Learn how to set up Next.js with three commonly used testing tools — Cypress, Playwright, Jest, and React Testing Library.
Read more >How to use Jest to test Express middleware or a function ...
The middleware is simple, just uses id and some key to generate a JWT, invoke error handler if there is an error. 2....
Read more >React app testing: Jest and React Testing Library
Jest is a test runner that finds tests, runs the tests, and determines whether the tests passed or failed. Additionally, Jest offers ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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.js
with the following content, that fixed the issue to me