2016-06-26 5 views
2

私はSinonにとって少し新しく、関数だけでなくその関数によって返された関数を偵察する必要があるシナリオにいくつかの問題を抱えています。具体的には、Azure Storage SDKを模擬して、キューサービスを作成したら、そのキューサービスから返されたメソッドも呼び出されるようにしています。ここで 関数sinonによって返された関数を詮索している

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

モックです:ここでは例です、私は queueServiceSpyが一度呼び出されていることを確認することができるよ

const Sinon = require('sinon'); 

module.exports = { 

    createQueueService:() => { 

     return { 

      createQueueIfNotExists: (queueName) => { 

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

      createMessage: (queueName, message) => { 

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

が、そのメソッドによって返される方法がある場合、私は決定問題を抱えています(createMessage)と呼ばれます。

これを設定するより良い方法はありますか、それとも私は何か不足していますか?

ありがとうございます!

答えて

2

あなたがしなければならないことは、他の場所への呼び出しを追跡できるスパイを返すようにサービス機能をスタブすることです。これを任意に深くネストすることができます(ただし、私はそれを強く推奨しません)。

のような何か:

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); 
関連する問題