2016-06-26 1 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

당신이해야 할 일은 스파이를 되찾기 위해 서비스 기능을 스텁 (stub)하여 다른 곳으로 전화를 추적 할 수 있습니다. 이것을 임의로 깊게 중첩시킬 수 있습니다 (그러나 나는 그것을 강력하게 억제 할 것입니다).

뭔가 같은 :

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