【发布时间】: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