4

Our Prisma setup is as follows:

// server/database/prisma.ts

import { Prisma } from 'database/generated/prisma-client';

const client = new Prisma({
  endpoint: PRISMA_ENDPOINT,
  secret: PRISMA_SECRET,
  debug: PRISMA_DEBUG,
});

// Add a proxy 'middleware' to the Prisma client to record query execution time
const prismaProxy = new Proxy(client, {
  get(client, endpoint) {
    const endTimer = metrics.prisma_call_duration_seconds.startTimer({ endpoint });
    return function (...args) {
      const result: Prisma = client[endpoint](...args);
      endTimer();
      return result;
    };
  },
});

export const prisma = prismaProxy;

I then have a utility that uses prisma that I would like to test:

// utils.ts

import { prisma } from 'database/prisma';

export const myFunc = async () => {
  const result = await prisma.items();

  if (items && items.length > 0) {
    return true;
  }

  return false;
}; 

How do I mock prisma in a test? In Jest 26, this worked:

// utils.test.ts

jest.mock('server/database/prisma');

import { prisma } from 'server/database/prisma';
import { myFunc } from 'server/utils';

describe.only('my test', () => {
  beforeAll(() => {
    prisma.items.mockImplementation(() =>
      Promise.resolve([
        {
          foo: 'bar',
        },
      ])
    );
  });

  test('it works', async () => {
    const items = await myFunc();
    expect(items).toBeTruthy();
  });
});

This no longer works in Jest 27 it seems. Having made no changes except upgrading Jest from v26 -> v27 the mocks no longer seem to take hold.

What is the proper way to mock prisma here?

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • What errors do you specifically get? You're just saying it doesn't work without explaining how – im_baby Jun 12 '21 at 00:30
  • 1
    @im_baby I don't get any errors. The code executes without issue but the mock doesn't take hold, and the code hits my actual prisma instance, returning an empty value from my local database which then causes the test to fail (since it expects values) – Matthew Herbst Jun 13 '21 at 01:17

0 Answers0