是否可以将测试文件放在Next.js 的pages 目录下?

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

我正在为 Next.js 应用程序中的 API 路由编写集成测试,我想知道将 index.test.ts 文件放在 /pages 目录。我希望测试尽可能接近文件,而不是必须将项目结构映射到 __test__ 目录中。

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

默认情况下,Next.js 将考虑 [=16= 下以 tsxtsjsxjs 结尾的任何文件] 文件夹,用于构建 pages/API 路由和路由。

来自 Custom Page Extensions 文档:

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

pages 文件夹(或任何子文件夹)中添加名为 index.test.ts 的文件会将该文件作为实际页面包含在内,并可能在构建时引发错误。

您可以通过修改 Next.js 期望使用 pageExtensions 属性 in next.config.js.

的扩展来规避此问题
module.exports = {
    // Default value is ['tsx', 'ts', 'jsx', 'js']
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}

使用此配置,只会考虑具有上述扩展名的页面。因此,您可以拥有以下 pages 文件夹结构,其中包含 co-located 个测试文件。

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

path.test.tsindex.test.ts 都将被忽略。