【问题标题】:spying on functions returned by a function sinon监视函数 sinon 返回的函数
【发布时间】:2016-06-26 16:48:37
【问题描述】:

我对 Sinon 有点陌生,在需要监视函数以及函数返回的函数的场景中遇到了一些麻烦。具体来说,我正在尝试模拟 Azure 存储 SDK,并确保一旦我创建了队列服务,队列服务返回的方法也会被调用。示例如下:

// test.js

// Setup a Sinon sandbox for each test
test.beforeEach(async t => {

    sandbox = Sinon.sandbox.create();
});

// Restore the sandbox after each test
test.afterEach(async t => {

    sandbox.restore();
});

test.only('creates a message in the queue for the payment summary email', async t => {

    // Create a spy on the mock
    const queueServiceSpy = sandbox.spy(AzureStorageMock, 'createQueueService');

    // Replace the library with the mock
    const EmailUtil = Proxyquire('../../lib/email', {
        'azure-storage': AzureStorageMock,
        '@noCallThru': true
    });

    await EmailUtil.sendBusinessPaymentSummary();

    // Expect that the `createQueueService` method was called
    t.true(queueServiceSpy.calledOnce); // true

    // Expect that the `createMessage` method returned by
    // `createQueueService` is called
    t.true(queueServiceSpy.createMessage.calledOnce); // undefined
});

这是模拟:

const Sinon = require('sinon');

module.exports =  {

    createQueueService: () => {

        return {

            createQueueIfNotExists: (queueName) => {

                return Promise.resolve(Sinon.spy());
            },

            createMessage: (queueName, message) => {

                return Promise.resolve(Sinon.spy());
            }
        };
    }
};

我能够确认 queueServiceSpy 被调用一次,但我无法确定该方法返回的方法是否被调用 (createMessage)。

有没有更好的方法来设置它还是我只是错过了什么?

谢谢!

【问题讨论】:

    标签: javascript testing sinon


    【解决方案1】:

    您需要做的是存根您的服务函数以返回一个间谍,然后您可以跟踪对其他地方的调用。您可以将其嵌套任意深(尽管我强烈反对这样做)。

    类似:

    const cb = sandbox.spy();
    const queueServiceSpy = sandbox.stub(AzureStorageMock, 'createQueueService')
        .returns({createMessage() {return cb;}}});
    
    const EmailUtil = Proxyquire('../../lib/email', {
        'azure-storage': AzureStorageMock,
        '@noCallThru': true
    });
    
    await EmailUtil.sendBusinessPaymentSummary();
    
    // Expect that the `createQueueService` method was called
    t.true(queueServiceSpy.calledOnce); // true
    
    // Expect that the `createMessage` method returned by
    // `createQueueService` is called
    t.true(cb.calledOnce);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2013-07-21
      • 2013-01-25
      • 2017-02-04
      • 1970-01-01
      相关资源
      最近更新 更多