marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
836 stars 57 forks source link

Private properties prevent casting #25

Closed Sytten closed 3 years ago

Sytten commented 4 years ago

This is a complex problem. I am a mocking a class from the Prisma library that looks like

export declare class PrismaClient<T extends PrismaClientOptions = {}, U = keyof T extends 'log' ? T['log'] extends Array<LogLevel | LogDefinition> ? GetEvents<T['log']> : never : never> {
  private fetcher;
  private readonly dmmf;
  private connectionPromise?;
  private disconnectionPromise?;
  private readonly engineConfig;
  private readonly measurePerformance;
  private engine: Engine;
  private errorFormat: ErrorFormat;
  get event(): EventDelegate;
}

I store an instance of this class in a context type:

export type Context = {
  prisma: PrismaClient;
};

For my tests, I created a mock type for the context:

export type MockContext = {
  prisma: MockProxy<PrismaClient>;
};

When I want to pass this mock context to the function to test, it is unable to cast the type to a Context because of the private properties:

Conversion of type 'MockContext' to type 'Context' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Types of property 'prisma' are incompatible.
    Type 'MockProxy<PrismaClient<{}, never>>' is missing the following properties from type 'PrismaClient<{}, never>': fetcher, dmmf, engineConfig, measurePerformance, and 3 more.

So for now I did a hack where I store a casted context in my mocked context:

export type MockContext = {
  prisma: MockProxy<PrismaClient>;
  ctx: Context;
};

export const createMockContext = (): MockContext => {
  const baseCtx = {
    prisma: mockDeep<PrismaClient>(),
  };

  const mockCtx = {
    ...baseCtx,
    ctx: baseCtx as Context,
  };

  return mockCtx;
};

But it would be great if I could just cast the mock context directly. Thanks a lot!

marchaos commented 3 years ago

This is fixed in 1.0.15. reopen this issue if you have any issues