Basel
Basel

Reputation: 1275

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.

Upvotes: 4

Views: 3645

Answers (2)

Orca
Orca

Reputation: 181

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.

Upvotes: 4

Basel
Basel

Reputation: 1275

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
})'

Upvotes: 2

Related Questions