tuxen
tuxen

Reputation: 21

Access local variable inside function and check ng-click in jasmine test with angularjs

Hello I have following code

myApp.controller('myctrl',function($scope,myservice){
  //where testClickEvent is ng-click from partials
 $scope.testClickEvent=function(args){      
   var setArg1=args[0];
   var params = {"myarg1":setArg1}      
  //rest call         
   myservice.testClickEvent(params).success(function(data){
      if(data.res==true)
      {
          $scope.somevariable="success";
      }

  }).error(function(error){    
      $scope.somevariable="failure";
    });
  }
});

I wanted to test it using jasmine that is

  1. testing ng-click event happened in partial ??
  2. how do i test $scope.somevariable and setArg1 has got proper value

    here i have used

    spyOn(scope,testClickEvent); 
    scope.testClickEvent(args);
    expect(scope.testClickEvent).toHaveBeenCalledWith(args);
    spyOn(myservice,testClickEvent); 
    myservice.testClickEvent(params);
    expect(myservice.testClickEvent).toHaveBeenCalledWith(params);
    

works but how to access result and async call back result????

Thanks in advance ! Your Help appreciated !

Upvotes: 2

Views: 1021

Answers (1)

link
link

Reputation: 2510

You would need to mock out the call using $httpBackend

https://docs.angularjs.org/api/ngMock/service/$httpBackend

The example from the angular page has the following 2 lines:

$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'}); $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');

The first one mocks out the response and responds with whatever object is specified The second one expects the server to be called with a specified object.

Hope this helps.

Upvotes: 1

Related Questions