Search code examples
typescriptjestjsmockingrelationshipprisma

Mock include property in findMany with Prisma


I have setup my project with TypeScript and Jest. I have a repository method that fetches all posts with their comments like so:

const data = await prisma.post.findMany({ include: { comments: true } })

After that I manipulate the comments via data.comments.map(...). This is where my tests fail. The errors I get tell me that data.comments is undefined.

This is how I mock the the findMany method call:

prismaMock.site.findMany.mockResolvedValue([
  {
    id: '1',
    title: 'mock',
    text: 'test',
    commentIDs: [],
  },
])

If I try to add countries: [] to the mock, then TypeScript complains by saying this property is not part of the Post type.

Is there a way to mock the data I get from the include part of the request?


Solution

  • Turns out all I had to do is store the mocked data in a variable without giving it a type:

    const mockedData = [
      {
        id: '1',
        title: 'mock',
        text: 'test',
        commentIDs: [],
      },
    ]
    

    And then:

    prismaMock.post.findMany. mockResolvedValue(mockedData)