【问题标题】:stubbing class and methods using sinon stub使用 sinon 存根的存根类和方法
【发布时间】:2021-06-10 12:31:39
【问题描述】:

在使用 sinon msk 客户端函数 connect() 和 send() 或 sendmessage() 时,我需要帮助。尝试了多种方法,但它仍然调用实际函数。请帮忙

这里在文件中编码sn-ps。

index.js

var KafkaConnection = require('./mskclient');
                var kafkaObj = new KafkaConnection(key.User, key.Secret);
            var res = await kafkaObj.connectProducer(event.body);

mskclient.js

class KafkaConnection {
  constructor(user, secret) {
    this.connection = new Kafka({
      authenticationTimeout: 5000,
      clientId: client_id,
      brokers: brokerlist.split(','),
      ssl: true,
      sasl: {
        mechanism: 'scram-sha-512',
        username: user,
        password: secret,
      },
    });
    this.producer = null;
  }

  async sendMessage(msgObj) {
    console.log('sendMessage');
    this.producer = this.producer || this.connection.producer();
    await this.producer.connect();
    await this.producer.send(msgObj);
  }

  async disconnect() {
    this.producer && (await this.producer.disconnect());
  }

  async connectProducer(event) {
    try {
      log.info('Sending Message');
      console.log('connectProducer');

      await this.sendMessage({
        topic: process.env.TOPIC_NAME,
        acks: 1,
        messages: [
          {
            key: 'test-key',
            value: JSON.stringify(event),
          },
        ],
      });
      await this.disconnect();
      log.info('Successfully sent message');
      return 0;
    } catch (e) {
      log.info('Message not sent to kafka..');
      log.error(e);
      await this.disconnect();
      return 1;
    }
  }
}

module.exports = KafkaConnection;

到目前为止,我尝试了以下方法,但它们都被称为 kafka 实际函数而不是存根

方法#1

const service = require('../index');
const KafkaConnection = require('../mskclient');

var kafkaObj = sinon.createStubInstance(KafkaConnection);

var res1 = service.handler(event).then(function () {
                       done();
                }).catch((error) => {
                    done();
                })

方法#2

const service = require('../index');
const KafkaConnection = require('../mskclient');

//var kafkaObj = sinon.createStubInstance(KafkaConnection);
   SMSStub = sinon.stub(KafkaConnection.prototype, 'KafkaConnection').callsFake(() => {
                return 1
            });

var res1 = service.handler(event).then(function () {
                       done();
                }).catch((error) => {
                    done();
                })

【问题讨论】:

  • “尝试了多种方法”请分享已经测试过的内容
  • 添加到主要问题中。请检查
  • 为了理解为什么这不起作用,我想你可能会从我的这个旧答案中得到一些东西:stackoverflow.com/questions/52587999/…。它基本上与运行时绑定有关。此外, createStubInstance 并没有像您认为的那样做。它不“包装”构造函数,它只是一个辅助对象创建方法。

标签: javascript node.js sinon sinon-chai


【解决方案1】:

首先,在自己的导入连接类上独立服务。

const service = require('../index'); // <-- import '../mskclient' and create obj
const KafkaConnection = require('../mskclient');

即使你交换它们

const KafkaConnection = require('../mskclient');

const kafkaObj = sinon.createStubInstance(KafkaConnection);

const service = require('../index'); // <-- it is still importing the original mskclient

来自https://sinonjs.org/how-to/stub-dependency/,如果你真的想存根依赖,你必须导出一个可变对象:

// mskclient.js
module.exports = {
  KafkaConnection: class KafkaConnection {},
};

// service.js
const mod = require('./mskclient');

module.exports = function run() {
  const conn = new mod.KafkaConnection();
  conn.doSomething();
}

但如果你使用jest,你可以

jest.mock('../mskclient');
// or
jest.mock('../mskclient', () => jest.fn(() => ({
  connectProducer: jest.fn(),
})));

const service = require('../index'); // <-- import '../mskclient' and create obj
const KafkaConnection = require('../mskclient');

// es6
import service from '../';
import KafkaConnection from '../mskclient';

jest.mock('../mskclient', () => jest.fn(() => ({
  connectProducer: jest.fn(),
})));

查看:https://jestjs.io/docs/next/es6-class-mocks#automatic-mock

【讨论】:

    【解决方案2】:

    您好,根据我对您问题的理解,我认为这就是您要查找的内容:

    sinon.stub(KafkaConnection.prototype, 'connectProducer').callsFake(() => {
      return 1;
    })
    sinon.stub(KafkaConnection.prototype, 'sendMessage').callsFake(() => {})
    

    sinon.stub 的第二个参数应该是您要模拟的函数的名称。

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2015-04-18
      • 2018-06-20
      • 1970-01-01
      • 2016-09-25
      • 2016-01-02
      • 2014-07-17
      • 2014-08-08
      • 2017-07-09
      相关资源
      最近更新 更多