我对 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
)。
是否有更好的设置方法,还是我只是遗漏了什么?
谢谢!
最佳答案
您需要做的是 stub 您的服务函数以返回一个 spy ,然后您可以跟踪对其他地方的调用。您可以将其嵌套任意深(尽管我强烈反对这样做)。
类似于:
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);
关于javascript - 监视函数 sinon 返回的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38040828/