是否可以测试Next.js的13个API路由处理程序?



尝试用Jest测试一个非常简单的路由:

import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ success: true })
}

但是当我在测试中调用await GET()时,我得到以下错误:

ReferenceError: Request is not defined

> 1 | import { NextResponse } from 'next/server'
| ^

我尝试传递一个请求对象到处理程序,然后用node-mocks-http模拟它,但发生同样的错误。

这些处理程序如何进行单元测试?

花了好几个小时。通过添加jest-environment-node测试环境解决使用问题:

npm i -D jest-environment-node

确保testEnvironment: "node"jest.config.js(而不是js-domjest-environment-jsdom)。

希望对你有帮助。

我也有同样的问题

ReferenceError: Response is not definedJest

和I解析为:

yarn install -D isomorphic-fetch

然后导入到测试文件

进口"isomorphic-fetch">

的例子:

...
import { checkAuthenticated } from '@api/is-authenticated';
import 'isomorphic-fetch';
jest.mock('@database/video.repo');
...

最新更新