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

Time:01-25

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);
  });
});

CodePudding user response:

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.

  •  Tags:  
  • Related