Skip to content

Deep mocking

Course: Testing in the MERN Stack - chapter 9

Another way to mock variables is to let vitest figure out the types and mock out all the attributes of the object being mocked.

For example, the prismaClient object has a lot of functions -

console.log(Object.keys(prismaClient))

What if we could mock out all these keys in a single function call?

  • Install vitest-mock-extended
npm i -D vitest-mock-extended
  • Create __mocks__/db.ts
import { PrismaClient } from '@prisma/client'
import { beforeEach } from 'vitest'
import { mockDeep, mockReset } from 'vitest-mock-extended'
export const prismaClient = mockDeep<PrismaClient>()
  • Remove the mock we added in index.test.ts , simply add a vi.mock("../db")
// vi.mock('../db', () => ({
// prismaClient: { sum: { create: vi.fn() }}
// }));
vi.mock('../db');
  • Try running the tests
npm run test

What if we are using the return value from the database call?

$1b