Skip to content

Instantly share code, notes, and snippets.

@joaobispo2077
Created July 3, 2023 12:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joaobispo2077/97cb6d5734cab1e6d2979d2487ee8a8d to your computer and use it in GitHub Desktop.
Save joaobispo2077/97cb6d5734cab1e6d2979d2487ee8a8d to your computer and use it in GitHub Desktop.
Sequelize and Prisma Mock Factory for Nest.js
import { PrismaClient } from '@prisma/client';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { PrismaService } from 'src/shared/services/prisma.service';
type CreatePrismaProviderMockResponse = {
provide: typeof PrismaService;
useValue: DeepMockProxy<PrismaClient>;
};
export const createPrismaMock = (): DeepMockProxy<PrismaClient> => {
return mockDeep<PrismaClient>();
};
export const createPrismaProviderMock =
(): CreatePrismaProviderMockResponse => ({
provide: PrismaService,
useValue: createPrismaMock(),
});
import { getModelToken } from '@nestjs/sequelize';
export type CreateSequelizeModelMockInput = {
model: Function;
mockValues?: Record<string, jest.Mock<any, any>>;
};
export type CreateSequelizeModelMockResponse = {
provide: string;
useValue: Record<string, jest.Mock<any, any>> | jest.Mock<void, []>;
};
const defaultUseValue = {
build: jest.fn().mockReturnValue({
save: jest.fn().mockResolvedValue({
get: jest.fn().mockReturnValue({}),
}),
}),
findOne: jest.fn(() => ({
get: jest.fn().mockReturnValue({}),
update: jest.fn().mockResolvedValue({
get: jest.fn().mockReturnValue({}),
}),
destroy: jest.fn().mockResolvedValue({}),
})),
findAndCountAll: jest.fn(() => ({
rows: [].map((execution) => ({
get: jest.fn(() => execution),
})),
count: 0,
})),
};
export const createSequelizeModelMock = ({
model,
mockValues,
}: CreateSequelizeModelMockInput): CreateSequelizeModelMockResponse => {
const useValue = mockValues ?? defaultUseValue;
return {
provide: getModelToken(model),
useValue,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment