dimanche 26 juin 2016

spying on functions returned by a function sinon

I'm a bit new to Sinon and having some trouble with the scenario where I need to spy on not only a function, but the functions returned by the function. Specifically, I'm trying to mock the Azure Storage SDK and ensure that once I've created a queue service, that the methods returned by the queue service are also called. Here's the example:

// 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
});

Here's the mock:

const Sinon = require('sinon');

module.exports =  {

    createQueueService: () => {

        return {

            createQueueIfNotExists: (queueName) => {

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

            createMessage: (queueName, message) => {

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

I'm able to confirm that the queueServiceSpy is called once, but I'm having trouble determining if the methods returned by that method are called (createMessage).

Is there a better way to set this up or am I just missing something?

Thanks!

Aucun commentaire:

Enregistrer un commentaire