mardi 2 août 2016

How, using sinon, to test if a method will be invoked

I'm trying to use sinon to verify that certain steps in a procedure are executed, I don't know when exactly are the steps executed, I just want to confirm that the method I'm testing will invoke the given function.

Here is what I currently do:

describe('Native calls handling', function() {

    var ctrl;
    var notificationsMock;

    before(function() {
        notificationsMock = sinon.mock(notifications);
    });

    after(function() {
        notificationsMock.restore();
    });

    beforeEach(function() {
        var $placeholder = document.createElement('div');
        var nav = new CoreNavigation({});
        ctrl = new EthernetController($placeholder, notifications, null, nav);
    });

    afterEach(cleanUp);

    // What I currently do
    it('Should perform internet check on `Connected` event', function(done) {
        var errorTimeout = setTimeout(function() {
            internetCheck.restore();
            done(new Error('Assertion failed, internetCheck was not executed'));
        }, 1500);

        var internetCheck = sinon.stub(ctrl, 'internetCheck', function() {
            clearTimeout(errorTimeout);

            internetCheck.restore();
            done();

            return Promise.resolve(true);
        });

        app.notify('system:ethernet:connected');
    });

    // Functionality I'm looking for
    it('Should perform internet check on `Connected` event', function(done) {
        var internetCheck = sinon.stub(ctrl, 'internetCheck', function() {
            return Promise.resolve(true);
        });

        // Fail the test if the function is not called within $ ms
        // Also restore the stub
        internetCheck.cancelationTime = 1500;

        // Trigger the assertion after/if the function is called
        internetCheck.whenCalled(function(params...) {// assertion })
            .timedOut(done);


        app.notify('system:ethernet:connected');
    });
});

The Connected event will trigger an async procedure that in the end will perform internetCheck
Is there something similar to what I'm looking for

Aucun commentaire:

Enregistrer un commentaire