【问题标题】:Writing test case using Sinon NodeJs使用 Sinon NodeJs 编写测试用例
【发布时间】:2021-11-28 23:36:05
【问题描述】:

在使用第三方库 (Kafkajs) 时,我正在为一些嵌套函数编写单元测试用例。测试用例首先创建一个对象,然后在其中调用一个类对象,然后从该类调用一个函数。此完整代码在第三方 SDK 中。

下面的代码是这样的

KafkaWrapper.ts

export class KafkaWrapper {
  kafkaInstance: any;

  constructor() {
    this.kafkaInstance = new Kafka({
      clientId: Config.serviceSettings.serviceTag,
      brokers: [Config.kafkaBrokers!],
      logLevel: logLevel.ERROR,
      logCreator: CustomLogCreator,
    });
  }
}

然后我有另一个 kafka-consumer.ts 文件,它在上面的类中使用,例如

const kafkaEvent = new KafkaWrapper();
const consumer = kafkaEvent.kafkaInstance.consumer({ groupId: Config.cdnPurgeConsumerGroup });
export default class CDNPurgeJobConsumer {
  public static async brokerConnection(): Promise<void> {
    console.log('Broker connection');
    await consumer.connect();
  }
}

我写到现在的测试用例是

  it('create fake connection with kafka broker', async function () {
    const stub = sandbox.stub(Kafka, 'consumer').returns({
      connect: sinon.fake()
    });
    await CDNPurgeJobConsumer.brokerConnection();
    expect(stub.calledOnce).to.equal(true);
    stub.restore();
  });

我也试图伪造 KafkaWrapper 函数,但它也没有为我工作。

这里我想模拟连接函数,因为Kafka 类来自第三方库。 第三方库名称为kafkajs,版本为1.15.0。

我曾尝试在 Kafka 上存根和天空,但每次都失败。

【问题讨论】:

  • 你能分享一下你现在能写什么单元测试吗?虽然失败了?
  • 用我写的测试用例更新了帖子描述。

标签: node.js unit-testing sinon


【解决方案1】:

@Techno Crazzyyyy 你可以在这里做的是

spyOn(KafkaWrapper.prototype, "kafkaInstance").and.returnValue({
                consumer: function () {
                    return {
                        connect: function () {
                            return Promise.resolve({})
                        }
                    }
                }
            });

虽然我在这里使用 jasmine,但这应该可以帮助您在这里窥探您的依赖关系。

【讨论】:

  • @techno-crazzyyyy 如果您遇到任何问题,或者您希望有任何改进,请告诉我。
  • 感谢您查看此内容。实施此操作后,我收到此错误Attempted to wrap undefined property kafkaInstance as function kafkaInstance 是 KafkaWrapper 类中的一个变量。
  • 我也试过 const stub = sandbox.stub(KafkaWrapper.prototype, 'kafkaInstance').get(() => { return { consumer: function () { return { connect: async function () { Promise.resolve({}); }, }; }, }; });但它也给了我Cannot stub non-existent property kafkaInstance
  • 好的,让我检查一次..
  • 这个解决方案可以正常工作,我在 brokerConnection 函数中声明了 kafkaEventconsumer,但我需要按照描述的方式模拟代码
猜你喜欢
  • 1970-01-01
  • 2018-05-27
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2021-09-29
  • 2013-07-05
  • 1970-01-01
相关资源
最近更新 更多