Skip to content

CustomPrismaService unit testing #83

@coryoso

Description

@coryoso

Hi! Thank you for nestjs-prisma, has been a great addition to our stack so far!

We're using the CustomPrismaService because we need to extend the client. Sadly the unit test setup does not work, i'm struggling with mocking the client. Right now it errors with TypeError: Cannot read properties of undefined (reading 'user') as the client is always undefined.

The userService looks like this:

@Injectable()
export class UsersService {
	constructor( 
		@Inject("PrismaService")
		private readonly prismaService: CustomPrismaService<ExtendedPrismaClient>, 
	) {}

        findOne = async (id: string) => {
	        return this.prismaService.client.user.findFirst({
		        where: { id },
	        })
        }
}

The userService.spec.test file like this:

describe("Usersservice", () => {
	let service: UsersService
	let prisma: DeepMockProxy<CustomPrismaService<ExtendedPrismaClient>>

	beforeEach(async () => {
		const module: TestingModule = await Test.createTestingModule({
			imports: [
				CustomPrismaModule.forRootAsync({
					name: "PrismaService",
					isGlobal: false,
					useFactory: () => {
						return extendedPrismaClient
					},
				}),
			],
			providers: [
				UsersService, 
				{
					provide: PrismaService,
					useValue: {},
				}, 
			],
		})
			.overrideProvider(CustomPrismaService<ExtendedPrismaClient>)
			.useValue(mockDeep<PrismaClient>())
			.compile()

		service = module.get<UsersService>(UsersService)
		prisma = module.get<PrismaService>(PrismaService)
	})

        it("should find a user", async () => {
                const userID = "user-id"
                
                prisma.client.user.findFirst.mockResolvedValueOnce({
	                id: userID,
	                firstName: "John",
	                lastName: "Doe",
	                email: "[email protected]",
                })
                
                expect(service.test(userID)).toEqual(userID)
        })
})

Appreciative of any help, thank you so much!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions