Hi I have an angular service.
...
return {
    setMixpanel: function(searchObject){
                  searchObject["referrer"] ? mixpanel.register({"$referrer":searchObject["referrer"]}) : mixpanel.register({"$referrer":""});
    }
}
In my unit test I probably have to spyOn mixpanel along with register. But I need to somehow mock mixpanel.register. 
How do I mock mixpanel.register properly? Where does code go. 
I mocked it as follows:
var mixpanel={
      register : function(object){
        return object
      }
    };
But where do I put this code? Is it correct?
I hope someone can help me out here?!
EDIT: The test itself looks probably like this
it('should test', function(){
    spyOn(mixpanel,'register');
    redirectService.setMixpanel(search);
    expect(mixpanel.register).toHaveBeenCalledWith('...');
})
But in order to do that I need to mock mixpanel. If I just spyOn mixpanel, I will get an error.
You need to create a spyObject first. There's no need to mock your service
beforeEach(function () {
    myServiceSpy = jasmine.createSpyObj('myService');
    module(function ($provide) {
        $provide.value('myService', myServiceSpy);
    });
});
Test
describe("myService", function() {
   it("calls the getUser() function", function() {
      /* Maybe this line unnecessary, cant try it atm */
      spyOn(service, "getUser");
      expect(service.getUser).toHaveBeenCalled();
   });
});
If you want to test if mixpanel.register is called, you need to create a spy object of your mixpanel. With $provide you tell the test to use the spy instead of the real service. 
describe('mixPanel', function () {
   mixPanelSpy = jasmine.createSpyObj('mixPanel');
   beforeEach(module(function($provide) {
     $provide.value("mixpanel", mixPanelSpy);
   }));
   beforeEach(inject(function (_mixpanelService_) {
      mixpanelService = _mixpanelService_;
   }));
   it('should set mixpanel', function() {
       mixpanelService.setMixPanel('test');
       expect(mixpanel.register).toBeCalled();
   });
});
wrote that out of my mind, maybe there're some clashes you need to fix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With