Most examples I've seen of how to test a Prisma-injected NestJS Service (e.g. prisma-sample in testing-nestjs) are for "end to end" testing. They actually access the database, performing actual queries and then rolling back the results if necessary.
For my current needs, I want to implement lower-level "integration" testing.
As part of this, I want to remove Prisma from the equation. I want the focus to be on my service's functionality instead of the state of data within the database and Prisma's ability to return it.
One big win of this approach is that it obviates the need to craft "setup" queries and "teardown"/reset operations for specific tests. Instead, I'd like to simply manually specify what we would expect Prisma to return.
In an environment consisting of NestJS, Prisma, and Jest, how should I accomplish this?
UPDATE: The author of the testing-nestjs project pointed out in the comments that the project does have an example of database mocking. It looks nice! Others may still be interested in checking out the Gist that I've linked to as it includes some other useful functionality.
To get a reference to your service's prisma instance, use:
prisma = module.get<PrismaService>(PrismaService)
Then, assuming your function calls prisma.name.findMany(), you can use jest.fn().mockReturnValueOnce() to mock (manually specify) Prisma's next return value:
prisma.name.findMany = jest.fn().mockReturnValueOnce([
{ id: 0, name: 'developer' },
{ id: 10, name: 'architect' },
{ id: 13, name: 'dog walker' }
]);
(Of course, you would change prisma.name.findMany in the code above to match whatever function you're calling.)
Then, call the function on your Service that you're testing. For example:
expect(await service.getFirstJob("steve")).toBe('developer');
That's it! A full code example can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With