使用 mocha 在 node.js 中编写单元测试用例来模拟 azure 服务总线队列以接收消息

Writing a unit test case in node.js using mocha to mock a azure service bus queue to recive messages

我写了一个单元测试用例,但是它报错了。 请在下面找到代码

index.js

const { ServiceBusClient, ReceiveMode } = require("@azure/service-bus");

module.exports = async function (context, myTimer) {

// Define connection string and related Service Bus entity names here
const connectionString = process.env['serviceBusConnectionString'];
const queueName = process.env['serviceBusQueueName'];
const sbClient = ServiceBusClient.createFromConnectionString(connectionString);
const queueClient = sbClient.createQueueClient(queueName);
//const receiver = queueClient.createReceiver(ReceiveMode.receiveAndDelete);
const receiver = queueClient.createReceiver(ReceiveMode.peekLock);

const messages = await receiver.receiveMessages(1);
try {

    let payloads = [];
    messages.forEach((msg) => {
        payloads.push(msg.body);
    })

    await queueClient.close();
} catch (err) {
    context.log('Queue message status settle: abandon');
    await messages[0].abandon();
    console.log('Error ', err);
} finally {
    await sbClient.close();
    context.done();
}

};

这是单元测试文件,我得到了 error.Please 让我知道为什么我会收到这个错误enter image description here

indexTest.js:

beforeEach(() => {
        const sbClientStub = {
            createQueueClient: sinon.stub().returnsThis(),
            createReceiver: sinon.stub().returnsThis(),
            receiveMessages:sinon.stub(),
            close: sinon.stub(),
        };
        sinon.stub(ServiceBusClient, 'createFromConnectionString').callsFake(() => sbClientStub);
        const ctx = {};
        // const actual = await pushToQueue(message, ctx);
        // sinon.assert.match(actual, 2);
        sinon.assert.calledWithExactly(ServiceBusClient.createFromConnectionString, undefined);
        sinon.assert.calledWithExactly(sbClientStub.createQueueClient, undefined);
        sinon.assert.calledOnce(sbClientStub.createReceiver, undefined );
        //sinon.assert.calledWithExactly(sbClientStub.send.firstCall, { body: 'a' });
        //sinon.assert.calledWithExactly(sbClientStub.send.secondCall, { body: 'b' });
        sinon.assert.calledTwice(sbClientStub.close); 
    });

您应该将每个 sinon.stub() 替换为 sinon.spy()。存根将阻止调用方法的原始实现,但间谍会这样做。它们基本上具有相同的 API。

为了调用@azure/service-bus的原始方法,请确保@azure/service-bus的资源准备就绪,例如环境变量、服务帐户、队列等。

如果这样做,单元测试将不再孤立。其实它们不再是单元测试,而是集成测试,或者说e2e测试。