mardi 29 septembre 2015

Mocking multiple return values for a function that returns a success/error style promise?

NB: Code reproduced from memory.

I have a method generated by djangoAngular that has this signature in my service:

angular.module('myModule')
.service('PythonDataService',['djangoRMI',function(djangoRMI){
     return {getData:getData};

     function getData(foo,bar,callback){
         var in_data = {'baz':foo,'bing':bar};
         djangoRMI.getPythonData(in_data)
         .success(function(out_data) {
            if(out_data['var1']){
                 callback(out_data['var1']);
             }else if(out_data['var2']){
                 callback(out_data['var2']);
            }
         }).error(function(e){
            console.log(e)
         });    
    };
}])

I want to test my service in Jasmine, and so I have to mock my djangoAngular method. I want to call through and have it return multiple datum.

This is (sort of) what I have tried so far, reproduced from memory:

describe('Python Data Service',function(){
    var mockDjangoRMI,
    beforeEach(module('ng.django.rmi'));
    beforeEach(function() {
        mockDjangoRMI = {
            getPythonData:jasmine.createSpy('getPythonData').and.returnValue({
                success:function(fn){fn(mockData);return this.error},
                error:function(fn){fn();return}
            })
        }
        module(function($provide) {
            $provide.provide('djangoRMI', mockDjangoRMI);
       });
   });
   it('should get the data',function(){
       mockData = {'var1':'Hello Stackexchange'};
       var callback = jasmine.createSpy();
       PythonDataService.getData(1,2,callback);
       expect(callback).toHaveBeenCalled();
   })
})

But when I put another it block in with a different value for mockData, only one of them is picked up.

I'm guessing that because of the order of operation something is not right with how I'm assigning mockData. How can I mock multiple datum into my djangoRMI function?

Aucun commentaire:

Enregistrer un commentaire