lundi 28 décembre 2015

jasmine test function that returns a promise

I have the following function implementation

function getRepo(url) {
    var repos = {};

    if (repos.hasOwnProperty(url)) {
        return repos[url];
    }

    return $.get(url)
        .then(repoRetrieved)
        .fail(failureHandler);

    function repoRetrieved(data) {

        return repos[url] = data;
    }

    function failureHandler(err, xhr) {
        throw new Error(xhr.responseText);
    }
}

And i wrote the following tests:

describe('"getRepo" method', function() {
    var getDeffered;
    var $;

     beforeEach(function() {
         getDeffered = Q.defer();
         $ = jasmine.createSpyObj('$', ['get']);
         $.get.and.returnValue(getDeffered.promise);
     });

     it('should return a promise', function(){
         expect(getRepo('someURL')).toEqual(getDeffered.promise);
     });

});

And this test fails. I think because i call the then method.

It does not fail if function implementation is:

function getRepo(url) {
    return $.get(url);
}

this is the message jasmine throws when using Q.defer()

Expected { promiseDispatch : Function, valueOf : Function, inspect : Function }
to equal { promiseDispatch : Function, valueOf : Function, inspect : Function }.

And this is the message if i use jQuery Deferred:

Expected { state : Function, always : Function, then : Function, promise : Function, pipe : Function, done : Function, fail : Function, progress : Function } 
to equal { state : Function, always : Function, then : Function, promise : Function, pipe : Function, done : Function, fail : Function, progress : Function }.

jQuery Deferred test implementation:

describe('"getRepo" method', function() {
    var getDeffered;
    var $;

    beforeEach(function() {
        getDeffered = real$.Deferred();
        $ = jasmine.createSpyObj('$', ['get']);
        $.get.and.returnValue(getDeffered.promise());
    });

    it('should return a promise', function(){
        expect(getRepo('someURL')).toEqual(getDeffered.promise());
    });

});

Aucun commentaire:

Enregistrer un commentaire