morintd / prismock

A mock for PrismaClient, dedicated to unit testing.
https://www.npmjs.com/package/prismock
MIT License
167 stars 18 forks source link

`PrismockClient` type is incorrect #871

Open electrovir opened 3 months ago

electrovir commented 3 months ago

Problem

This type cast is incorrect: https://github.com/morintd/prismock/blob/1b3baeb75b4749cedd0482479a178e39a1f37a2b/src/lib/client.ts#L116

It's intersecting the PrismockData interface as a static interface, not an instance interface.

What I mean by that is that with the current types, this is a type error (but not a run-time error):

const client = new PrismockClient();
client.getData();

while this is not a type error but is a run-time error:

const client = new PrismockClient();
PrismockClient.getData();

Solution

You basically need to unwrap and rewrap the PrismaClient constructor so you can modify the returned instance type. There might be a more elegant way of doing this, but this is working for me:

import type {Constructor} from 'type-fest';

type RealPrismockClient = Constructor<
    PrismaClient & PrismockData,
    ConstructorParameters<typeof PrismaClient>
>;

Note that if you don't want to include the type-fest dependency, the Constructor type that it exports is as follows:

export type Constructor<T, Arguments extends unknown[] = any[]> = new(...arguments_: Arguments) => T;
morintd commented 2 months ago

Hello @electrovir , thanks a lot! I'll think about the best way to fix that and try to get something done in the next few days

JoeRoddy commented 6 days ago

may be related, getting this type error when I attempt to call .reset()

image

again, @morintd great work on this library, such a valuable tool <3

electrovir commented 5 days ago

Correct @JoeRoddy, the cause for that error you're seeing is the same.