【问题标题】:Using ConfigService in Unit Test - NestJS在单元测试中使用 ConfigService - NestJS
【发布时间】:2022-06-17 20:31:40
【问题描述】:

我有一个 Kafka ProducerService,它看起来像这样:

@Injectable()
export class ProducerService implements OnModuleInit, OnApplicationShutdown {
  private logger = new Logger(ProducerService.name);
  public readonly topic: string;
  private readonly url: string;
  private readonly clientId: string;
  private readonly scramUsername: string;
  private readonly scramPassword: string;
  private kafka: Kafka;
  private producer: Producer;

  constructor(private config: ConfigService) {
    this.url = this.config.get<string>('kafka.brokerUrl');
    this.topic = this.config.get<string>('kafka.topic');
    this.clientId = this.config.get<string>('kafka.clientId');
    if(this.config.get<boolean>('kafka.scram.enabled') == true) {
      this.scramUsername = this.config.get<string>('kafka.scram.username');
      this.scramPassword = this.config.get<string>('kafka.scram.password');
    } else {
      this.scramUsername = "";
      this.scramPassword = "";
    }
    this.kafka = new Kafka({
      brokers: [this.url],
      clientId: this.clientId,
    });
    this.producer = this.kafka.producer();
  }

我在KafkaModule 中导入了ConfigModule,这允许我在ProducerService 构造函数中注入ConfigService

如何充分测试这项服务? 我正在我的producer.spec.ts 文件中尝试这样基本的东西:

describe('ProducerService', () => {
  const config = new ConfigService()
  const client = new ProducerService(config)
  
  beforeEach(async () => {
    await client.onModuleInit();
  })

  it('Should connect', () => {
    expect(client).toBeDefined()
  })

但我一直无法将配置加载到测试对象中:

KafkaJSNonRetriableError: Failed to connect: broker at index 0 is invalid "undefined"

写。配置,我使用的是.yaml

【问题讨论】:

    标签: unit-testing apache-kafka nestjs nestjs-config


    【解决方案1】:

    您使用的是 Node 16 吗?我遇到了同样的问题,我使用 nvm 切换到节点 14。它现在可以工作了。

    不知道实际问题是什么,但这可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 2021-01-18
      • 2020-05-15
      • 2020-07-23
      • 2022-07-14
      • 2021-02-16
      • 2019-07-16
      • 2018-09-30
      • 2018-12-01
      相关资源
      最近更新 更多