Вы должны использовать библиотеку-заглушку / насмешку, такую как sinon. js. Вот модульный тест:
index.js
:
async function pushToQueue(messages, ctx) {
context = ctx;
const { ServiceBusClient } = require('@azure/service-bus');
const connectionString = process.env['serviceBusConnectionString'];
const queueName = process.env['serviceBusQueueName'];
const sbClient = ServiceBusClient.createFromConnectionString(connectionString);
const queueClient = sbClient.createQueueClient(queueName);
const sender = queueClient.createSender();
try {
for (let i = 0; i < messages.length; i++) {
const message = {
body: messages[i],
};
await sender.send(message);
}
await queueClient.close();
} finally {
await sbClient.close();
}
return messages.length;
}
module.exports = { pushToQueue };
index.test.js
:
const { pushToQueue } = require('.');
const sinon = require('sinon');
const { ServiceBusClient } = require('@azure/service-bus');
describe('60772165', () => {
it('should push to queue', async () => {
const sbClientStub = {
createQueueClient: sinon.stub().returnsThis(),
createSender: sinon.stub().returnsThis(),
send: sinon.stub(),
close: sinon.stub(),
};
sinon.stub(ServiceBusClient, 'createFromConnectionString').callsFake(() => sbClientStub);
const messages = ['a', 'b'];
const ctx = {};
const actual = await pushToQueue(messages, ctx);
sinon.assert.match(actual, 2);
sinon.assert.calledWithExactly(ServiceBusClient.createFromConnectionString, undefined);
sinon.assert.calledWithExactly(sbClientStub.createQueueClient, undefined);
sinon.assert.calledOnce(sbClientStub.createSender);
sinon.assert.calledWithExactly(sbClientStub.send.firstCall, { body: 'a' });
sinon.assert.calledWithExactly(sbClientStub.send.secondCall, { body: 'b' });
sinon.assert.calledTwice(sbClientStub.close);
});
});
Результаты модульного теста со 100% покрытием:
60772165
✓ should push to queue
1 passing (14ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
исходный код: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/60772165