Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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);
  });
});
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!