NextJS 14应用程序目录route.js测试失败与Vitest

ecbunoof  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(78)

如何测试route.js?

import { describe, expect, it, vi } from 'vitest'
import { POST } from './route'

describe('[POST] /api/test', () => {

  it('should respond with a `400` status code and error message', async () => {
    const request = new Request('http://localhost:3000/api/test', {
      method: 'POST'
    })
    const res = await POST(request)
    const body = await res.json()
    expect(res.status).toBe(400)
  })

})

字符串
它在.json()上失败,因为它在Request对象上不存在

export const POST = async (request: Request) => {
  const data = await request.json()
  ...
}


我使用vitest与jsdom环境。

v09wglhw

v09wglhw1#

经过一番折腾,答案是用NextRequest Package Request

import { NextRequest } from 'next/server'

const request = new NextRequest(
  new Request('http://localhost:3000/api/test', {
    method: 'POST'
  })
)

字符串
希望对你也有帮助

相关问题