监视函数sinon返回的函数
spying on functions returned by a function sinon
我对Sinon有点陌生,并且在我不仅需要监视函数,而且需要监视函数返回的函数的场景中遇到了一些麻烦。具体来说,我试图模拟Azure Storage 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
)时遇到了麻烦。
是否有更好的方法来设置这个,或者我只是错过了什么?
谢谢!
你需要做的是存根你的服务函数返回一个间谍,然后你可以跟踪调用到其他地方。你可以任意地嵌套它(尽管我强烈反对这样做)。
类似:
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);
相关文章:
- ES6构造函数返回基类的实例
- 从函数返回角度承诺
- 如何从jquery函数返回变量
- 根据是否解析了 Promise 从函数返回值
- Javascript函数返回未定义
- 如果函数返回True,则显示Javascript按钮
- Google Sheet自定义函数返回0
- 从Ajax函数返回值
- 使用for循环从Javascript中的函数返回多个值
- 谷歌地图:函数返回未定义的值在console.log中运行良好
- 从函数中的函数返回数组时出错
- 如何从嵌套的API函数返回值
- 从Mongoose结果匿名函数返回父函数
- 函数返回错误'令牌{'
- Jquery函数返回订单问题
- Mocha/Chai测试链接到函数返回断言错误
- 从异步函数返回值
- 函数返回后更新变量
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 将外部函数返回的id传递给内部函数