Is it possible to put test files under pages directory in Next.js?

TL;DR: While not possible by default, you can co-locate test files inside the pages folder by customising the pageExtensions option in next.config.js.


By default, Next.js will take into account any file ending with tsx, ts, jsx or js under the pages folder for the purpose of building pages/API routes and routing.

From the Custom Page Extensions documentation:

Next.js assumes every tsx/ts/jsx/js file in the pages directory is a
page or API route, and may expose unintended routes vulnerable to
denial of service attacks, or throw an error like the following when
building the production bundle

Adding a file named index.test.ts in the pages folder (or any subfolder) will include that file as an actual page, and potentially throw errors during build time.

You can circumvent this by modifying the extensions Next.js expects using the pageExtensions property in next.config.js.

module.exports = {
    // Default value is ['tsx', 'ts', 'jsx', 'js']
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}

With this configuration, only pages with the above extensions will be taken into account. So you could have the following pages folder structure, with co-located test files.

pages/
├─ api/
│   ├─ path.page.ts
│   └─ path.test.ts
├─ _app.page.ts
├─ _document.page.ts
├─ index.page.ts
└─ index.test.ts

Both path.test.ts and index.test.ts would be ignored.

Leave a Comment