英文:
How to test NextJS App Router API route with Jest
问题
以下是翻译好的内容:
我有一个非常简单的API路由,我想要测试:
文件 ./src/app/api/name
```typescript
import { NextResponse } from 'next/server';
export async function GET() {
    const name = process.env.NAME;
    return NextResponse.json({
        name,
    });
}
我尝试这样测试它:
import { GET } from './route';
describe('name', () => {
    it('should return url from environment variables', async () => {
        const result = await GET();
        const { name } = await result.json();
        expect(name).toEqual('test');
    });
});
但是然后出现了错误:
 FAIL  src/app/api/name/route.spec.ts
  ● Test suite failed to run
    ReferenceError: Response is not defined
       9 | }
      10 |
      at Object.Response (node_modules/next/src/server/web/spec-extension/response.ts:29:51)
      at Object.<anonymous> (node_modules/next/dist/server/web/exports/next-response.js:12:19)
      at Object.<anonymous> (src/api/name/route.ts:11:62)
      at Object.<anonymous> (src/api/name/route.spec.ts:5:16)
我尝试按照一些关于测试NextJS API路由的说明,但它们都基于页面路由。
我该如何正确测试这个?
<details>
<summary>英文:</summary>
I have a very simple API route which I would like to test:
File ./src/app/api/name
```typescript
import { NextResponse } from 'next/server';
export async function GET() {
    const name = process.env.NAME;
    return NextResponse.json({
        name,
    });
}
I have tried to test this like this:
import { GET } from './route';
describe('name', () => {
    it('should return url from environment variables', async () => {
        const result = await GET();
        const { name } = await result.json();
        expect(name).toEqual('test');
    });
});
But then an error is thrown:
 FAIL  src/app/api/name/route.spec.ts
  ● Test suite failed to run
    ReferenceError: Response is not defined
       9 | }
      10 |
      at Object.Response (node_modules/next/src/server/web/spec-extension/response.ts:29:51)
      at Object.<anonymous> (node_modules/next/dist/server/web/exports/next-response.js:12:19)
      at Object.<anonymous> (src/api/name/route.ts:11:62)
      at Object.<anonymous> (src/api/name/route.spec.ts:5:16)
I tried to follow some instructions on testing NextJS API routes, but they're all based on the Pages Router.
How can I properly test this?
答案1
得分: 1
我已找到解决方案。测试未能正常工作,因为我的jest配置将'testEnvironment'设置为'jest-environment-jsdom'。
在.spec.ts文件的顶部添加以下内容后,初始测试设置确实有效:
/**
 * @jest-environment node
 */
英文:
I have found the solution. The test didn't work, since my jest configuration sets 'testEnvironment' to 'jest-environment-jsdom'.
The initial test setup does work after adding the following to the top of the .spec.ts file:
/**
 * @jest-environment node
 */
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论