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?
Deep mocking
Section titled “Deep mocking”- 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
mockwe added inindex.test.ts, simply add avi.mock("../db")
// vi.mock('../db', () => ({// prismaClient: { sum: { create: vi.fn() }}// }));vi.mock('../db');- Try running the tests
npm run test
Problem
Section titled “Problem”What if we are using the return value from the database call?
$1b