I need to do some unit test to a kafka implementation in my project with NestJS but I don't know how to do it.
I have a Service
thats inject a Client Kafka
export class Service {
private static readonly logger = new Logger(ProducerService.name);
constructor(
@Inject('kafka-registrar') private client: ClientKafka,
private someOtherService: SomeOtherService,
) {}
Module
@Module({
imports: [
ClientsModule.register([
{
name: 'kafka-registrar',
transport: Transport.KAFKA,
options: {
client: {
clientId: 'hero',
brokers: ['localhost:9092'],
},
consumer: {
groupId: '1',
},
},
},
]),
SomeOtherService,
],
providers: [Service],
})
export class Module {}
Unit test
describe('Test Controller', () => {
let clientKafka: ClientKafka;
let someOtherService: SomeOtherService;
let producerService: ProducerService;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
ProducerService,
{
provide: SchemaRegistryService,
useValue: {
encodeWithId: jest.fn(),
},
},
{
provide: ClientKafka,
useValue: {
emit: jest.fn(),
},
},
],
}).compile()
clientKafka = moduleRef.get(ClientKafka);
schemaRegistryService = moduleRef.get(SchemaRegistryService);
producerService = moduleRef.get(ProducerService);
});
The project give me this error:
Error: Nest can't resolve dependencies of the ProducerService (?, SchemaRegistryService). Please make sure that the argument kafka-registrar at index [0] is available in the RootTestModule context.
Potential solutions:
- If kafka-registrar is a provider, is it part of the current RootTestModule?
- If kafka-registrar is exported from a separate @Module, is that module imported within RootTestModule?
@Module({
imports: [ /* the Module containing kafka-registrar */ ]
})
I don't know how to resolve this in NestJS. For example in Java,I belive that this can be with @Mock ClientKafka clientKafka
bit I dont have any other experience with NestJS... Please helpme! :)