Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock Prisma client with es6 (Without typescript) in jest?

The Prisma Documentation has examples of mocking the client and doing unit testing using jest and typescript. Is there any way to mock the client in jest without using TypeScript?

I would be grateful if you can give a simple example.

Small Thing to add: I am using dependency injection in my project in all the functions that use the prisma.

like image 434
Basel Akasha Avatar asked Oct 19 '25 19:10

Basel Akasha


2 Answers

I've made a Nodejs demo which is equivalent to the official guide - Unit testing (TypeScript version).

See: https://github.com/OctobugDemo/nodejs-prisma-unit-test

It might help.

like image 112
Orca Avatar answered Oct 22 '25 09:10

Orca


My solution for now: I am manually mocking the database object and passing it to the function that uses it: I am not sure how useful this but it helps avoid making calls to the real database.

const mocked_db = {
    user: {
        findFirst: jest.fn(() => Promise.resolve(
            {
                id: 2,
                first_name: "Basel",
                last_name: "Akasha"
            }
        ))
    }
}

it("It should work blah blah bla", async () => {
    let user_details= {
       id: 2,
       first_name: "Basel",
       last_name: "Akasha"
    }
    
    let signup = await getUser(
        mocked_db // takes thew DB object is a parameter (normally you would pass your Prisma client instance)
    )

    await expect(.... // whatever you'r expect is
})'
like image 30
Basel Akasha Avatar answered Oct 22 '25 10:10

Basel Akasha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!