javascript - 监视函数 sinon 返回的函数

标签 javascript testing sinon

我对 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/

相关文章:

javascript - 对菜单使用条件语句

javascript - 未调用方法上的 Sinon.spy

javascript - Mocha 和 Sinon 测试 Promise 超时

javascript - 我想将 cmd 输出写入文件而不是 stdout

ruby-on-rails - 初始化后的工厂女孩

visual-studio-2010 - VS2010 中的性能测试

javascript - 如何测试需要jquery的ES6类?

javascript - 如何在更新面板回发后执行 javascript 回调?

javascript - $ ('body' ).click ('li' , func) 与 $ ('li' ).click(func),第二个选项不起作用?

javascript - typescript | JavaScript | Angular 2 | @Output 与 @Input