Created
July 3, 2023 12:36
-
-
Save joaobispo2077/97cb6d5734cab1e6d2979d2487ee8a8d to your computer and use it in GitHub Desktop.
Sequelize and Prisma Mock Factory for Nest.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(), | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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