P
Prisma7mo ago
bjn

In tests, how can I verify a PrismaPromise was actually executed?

I had an application bug just now because I hadn't realized that Prisma's promises don't immediately execute. The database queries only run when the promise is awaited, or when .then() or .catch() is called. This is easy to deal with, and now I know, but I want to cover this in my tests. I'm using Jest, and I'm doing a mockDeep from jest-mock-extended. It's not enough to just test expect(mockDb.myModel.delete).toHaveBeenCalled() because that doesn't assert that it was actually awaited. Is there a straightforward way to test for this? (Maybe this is more of a Jest question than a Prisma one...)
3 Replies
Prisma AI Help
Prisma AI Help7mo ago
You decided to hold for human wisdom. We'll chime in soon! Meanwhile, #ask-ai is there if you need a quick second opinion.
bjn
bjnOP7mo ago
I tried the following.
it("deletes the matching row", async () => {
const promise = Promise.resolve(response);
const promiseSpies = [
jest.spyOn(promise, "then"),
jest.spyOn(promise, "catch"),
jest.spyOn(promise, "finally"),
];
mockDb.myModel.delete.mockReturnValue(promise as any);

await runMyFunction(arg1, arg2);
expect(mockDb.myModel.delete).toHaveBeenCalledTimes(1);

// Ensure the query was actually fired
expect(promiseSpies.some((spy) => spy.mock.calls.length > 0)).toBe(true);
});
it("deletes the matching row", async () => {
const promise = Promise.resolve(response);
const promiseSpies = [
jest.spyOn(promise, "then"),
jest.spyOn(promise, "catch"),
jest.spyOn(promise, "finally"),
];
mockDb.myModel.delete.mockReturnValue(promise as any);

await runMyFunction(arg1, arg2);
expect(mockDb.myModel.delete).toHaveBeenCalledTimes(1);

// Ensure the query was actually fired
expect(promiseSpies.some((spy) => spy.mock.calls.length > 0)).toBe(true);
});
It notices when then/catch/finally are called, but it does not notice if the promise is awaited.
Nurul
Nurul6mo ago
I am not aware of any straightforward way in jest-mock-extended or Jest to assert that a returned promise was actually awaited or consumed with .then()/.catch(). The mock only records the function call, not how the returned promise is handled.

Did you find this page helpful?