Skip to content

Mocking dependencies

Course: Testing in the MERN Stack - chapter 8

Ref - https://vitest.dev/guide/mocking.html

When writing unit tests , you mock out all external service calls.

This means you test the core of your logic, and assume the database calls would succeed.

This is done so tests can run without starting a database / external services

Mocking, as the name suggests, means mocking the behaviour of a file/class/variable when tests are running.

To mock out the prismaClient, you can add the following code to the top of index.test.ts

vi.mock('../db', () => ({
prismaClient: { sum: { create: vi.fn() }}
}));

Since we know we are only calling

prismaClient.sum.create

I have mocked the implementation of that function. A mock does nothing and returns undefined when the function call succeeds.

Try running npm run test now. It should succeed

💡 Can you guess the two problems that exist here?

  1. What if I want to use the value that the database call returns? Right now, it will return undefined while a real DB call would return some real data
  2. I have to constantly keep upgrading the mock since in the future I might use the findOne function, then might add a new table called users …