alonisser
alonisser

Reputation: 12088

Testing a service call to Restangular with nested spy

the service I'm testing has this function (for example):

doSomething : function(userID,boolean){

                var t = otherService.getSomething();
                var params = somedata;
                var deferred = $q.defer();
                if (boolean){
                    Restangular.one("users",userID).post("copy",params).then(function(data){...

And I just want to with a spy on Restangular to see if it gets the right params, endpoints etc to use.

so I made a restangular mock:

mockRestangular = {
                    one:function(){return this}
                    },



                    post:function(){

                    },
                    all:function(){

                    }
                };
                    },

//also tried:
// one: function(){return {post:function(){}};}


                };

but I can't set a jasmine spy on the nested post in the mock:

spyOn(mockRestangular.one,'post') I get post() method does not exist

and the function call fails too

someService.doSomething(params)

because it can find the post method.

Notice that I need the post method to be nested to the one method. If i just turn one into an object It would fail with a missing one method.

Guess I'm missing something obvious but I've been wrapping my mind around this all morning and failed completely

EDIT:

Adding andCallThrough() to the spy had all the pieces settled in the right direction. I'll update in an answer if someone would come looking some day.

Upvotes: 2

Views: 3436

Answers (1)

alonisser
alonisser

Reputation: 12088

The solution was: adding to the first spy:

spyOn(mockRestangular,'one').andCallThrough();

and change the object to:

mockRestangular = {
                    one:function(){
                         return this //since this can be chained to another one or post method, this way it always has one...
                    },



                    post:function(){

                    },
                    all:function(){

                    }
                };

Edit: I moved to Sinon, jasmine spys are too limited anyway.

Edit: This is how to move to chai+sinon in karma/jasmine testing (without moving to mocha..):

npm install karma-sinon-chai

Add to karma.conf.js:

add it in the plugins list

'karma-sinon-chai'

and in change the framework:

    frameworks: ['jasmine','sinon-chai'],

Now add a chai-helper.js file (name doesn't matter) to the files array in the karma.conf file.

the file should include:

var should = chai.should(); //you don't need all three, just the style you prefer.. 
var expect = chai.expect; //notice that using would break existing test and need you to do a little rewrite to fix the matchers. if you don't want to, comment this line out
var assert = chai.assert;

Upvotes: 2

Related Questions