Having the following definition of a global dynamic module:
// prisma.module.ts
import { DynamicModule, Global, Module } from '@nestjs/common'
import { PrismaService } from 'nestjs-prisma'
@Global()
@Module({})
export class PrismaModule {
static register(options: {
databaseUrl: string
}): DynamicModule {
return {
module: PrismaModule,
providers: [
{
provide: PrismaService,
useFactory: () =>
new PrismaService({
prismaOptions: {
datasources: {
db: {
url: options.databaseUrl,
},
},
},
}),
},
],
exports: [PrismaService],
}
}
}
I’m using Test.createTestingModule
to compile and test a module which is not a top-level AppModule
(let’s say MyModule
). This module depends on the global, dynamic module PrismaModule
, so I had to override it using the trick mentioned in this GitHub issue:
// app.module.ts
export const prismaModule = PrismaModule.register({
databaseUrl: process.env.DB_URL,
})
@Module({
imports: [
// ...
prismaModule,
// ...
],
})
export class AppModule {
constructor() {}
}
// my-module.test.ts
import { prismaModule } from '../app.module'
// ...
const mockPrismaModule = PrismaModule.register({
databaseUrl: "<some connection string>",
})
const moduleRef = await Test.createTestingModule({
imports: [prismaModule],
controllers: [MyController],
providers: [MyService],
})
.overrideModule(prismaModule)
.useModule(mockPrismaModule)
.compile()
const prismaService = mockPrismaModule.<...>
Is there a way to get access to an instance of PrismaService
of mockPrismaModule
that the dynamic PrismaModule
creates during register()
? I’ve tried using mockPrismaModule.get(PrismaService)
but it doesn’t seem like it can be used in a way as you’d use the result of Test.createTestingModule()
.
You should be fine to use moduleRef.get(PrismaService, { strict: false })