存根 class 和使用 sinon 存根的方法

stubbing class and methods using sinon stub

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

这里是文件中的代码片段。

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 actual 函数而不是 stubs

方法 #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();
                })

你好,根据我对你问题的理解,我想这就是你要找的:

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

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

首先,服务自己独立导入连接class。

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