Next.js: ignore test files in route folders (pages)
When working with Next.js, I prefer to keep my test files right next to the code they’re testing. For example:
search.ts
search.test.ts
This makes it easy to find tests, spot missing coverage, and avoids duplicating folder structures in a separate __tests__
directory.
But there’s a catch: Next.js routes (pages) from every file in the pages
directory.
Next.js: Batteries Footguns Included
Next.js treats every file in the pages
directory as a route, so welcome.test.tsx
becomes a /welcome.test
route.
src/components/Foo.tsx
src/components/Foo.test.tsx // fine, not a route
src/pages/welcome.tsx
src/pages/welcome.test.tsx // Next.js tries to make a /welcome.test route
This ends up bundling test code into your client bundle! Assuming this doesn’t fail outright during a build, you can wind up exposing sensitive code this way.
The official workaround is to add a .page
segment to...