我需要使用 NestJS 对我的项目中的 kafka 实现进行一些单元测试,但我不知道该怎么做。
我有一个Service
多数民众赞成注入客户端卡夫卡
export class Service {
private static readonly logger = new Logger(ProducerService.name);
constructor(
@Inject('kafka-registrar') private client: ClientKafka,
private someOtherService: SomeOtherService,
) {}
模块
@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 {}
单元测试
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);
});
该项目给我这个错误:
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 */ ]
})
我不知道如何在 NestJS 中解决这个问题。例如在 Java 中,我相信这可能是因为@Mock ClientKafka clientKafka
我对 NestJS 没有任何其他经验......请帮助我!:)