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
Section titled “Mocking”Mocking, as the name suggests, means mocking the behaviour of a file/class/variable when tests are running.

Creating a mock
Section titled “Creating a mock”
Mocking our prismaClient
Section titled “Mocking our prismaClient”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.createI 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

Problems
Section titled “Problems”💡 Can you guess the two problems that exist here?
- What if I want to use the value that the database call returns? Right now, it will return
undefinedwhile a real DB call would return some real data - I have to constantly keep upgrading the
mocksince in the future I might use thefindOnefunction, then might add a new table calledusers…