Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm writing integration tests for the API routes in a Next.js application and I'm wondering if there is any problem with putting the index.test.ts file under the /pages directory. I'd prefer the test to be as close to the file as possible rather than having to map the project structure inside __test__ directory.

./pages/api/path/index.ts

handler.get(async (req: NextApiRequest, res: NextApiResponse) => {
  ...
});

export default  handler;

./pages/api/path/index.test.ts

import { testClient } from "__test__/utils/testClient";

describe("Testing API  POST: /api", () => {
  test("Should return 401 when not authenticated", async () => {
    const request = testClient({ handler });
    const res = await request.post("/api/applications");
    expect(res.status).toEqual(401);
  });
});
like image 877
Tiago Redaelli Avatar asked Dec 06 '25 01:12

Tiago Redaelli


1 Answers

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.

like image 167
juliomalves Avatar answered Dec 08 '25 13:12

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!