You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest中Mock Prisma findMany的include关联数据?

问题分析与解决方案

核心问题1:Mock对象匹配错误

你实际调用的是prisma.post.findMany,但Mock的是prismaMock.site.findMany,两者不匹配,导致Mock未生效,返回的数据自然没有comments属性。

核心问题2:数据处理逻辑错误

prisma.post.findMany返回的是数组,你直接访问data.comments会报错,因为数组本身没有comments属性,应该遍历数组中的每一篇文章,再访问单篇文章的comments。

核心问题3:TypeScript类型匹配问题

当使用include: { comments: true }时,Prisma返回的类型不是默认的Post,而是包含关联数据的Prisma.PostGetPayload<{ include: { comments: true } }>,直接添加comments属性会触发类型校验错误,需要通过类型断言或预定义类型解决。


完整修正方案

  1. 修正Mock对象
    将Mock的site改为post,确保和实际调用的方法一致,同时通过类型断言绕过类型校验:

    // 正确写法
    prismaMock.post.findMany.mockResolvedValue([
      {
        id: '1',
        title: 'mock',
        text: 'test',
        commentIDs: [],
        comments: [] // 添加comments关联数据
      }
    ] as Prisma.PostGetPayload<{ include: { comments: true } }>[])
    
  2. 修正数据处理逻辑
    遍历返回的文章数组,逐个处理单篇文章的评论:

    const data = await prisma.post.findMany({ include: { comments: true } })
    // 正确写法
    data.forEach(post => {
      post.comments.map(comment => {
        // 处理评论逻辑
      })
    })
    
  3. 更优雅的类型处理方式
    如果你觉得类型断言不够直观,可以提前定义符合返回类型的变量:

    import type { Prisma } from '@prisma/client'
    
    const mockPostsWithComments: Prisma.PostGetPayload<{ include: { comments: true } }>[] = [
      {
        id: '1',
        title: 'mock',
        text: 'test',
        commentIDs: [],
        comments: []
      }
    ]
    
    prismaMock.post.findMany.mockResolvedValue(mockPostsWithComments)
    

内容的提问来源于stack exchange,提问作者Emanuil Gospodinov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:01:40