mardi 30 juin 2015

Angular JS unit test for web-service response without mocking

I'm making a unit test for angular js application in Karma.

There is a part where my controller function makes a web-service call to the server. I would like to verify the response data from the server side using unit testing.

I have looked at many tutorials. However, they are suggesting to make an angular mock service call to achieve this.

I wonder these mock service calls don't make any actual calls to the server. Instead, they are using sample response data, which is hard coded in unit test code.

I would like to unit test the original workflow (make an actual call to the server) instead of getting the responds from hard coded one.

Any help on this is appreciated.

Code: The below is working fine using mocked response data.

Controller

$scope.Login = function () {
  loginService.then(function (loginServiceObj) {
   loginServiceObj.AuthenticateUserLogin($scope.userName, $scope.password).success(function (data) {
    $scope.responseData = data;
    if (data["statusCode"]) {
     $modalInstance.close(data);
    } else {
     $scope.errorMessage = data['errorMessage'];
    }
   }).error(function () {
    $scope.errorMessage = "An error occured while processing!";
   });
  });
 };

Testing Function:

describe("Login Controller Spec", function () {

 beforeEach(module('ui.bootstrap'));
 beforeEach(module('ngStorage'));
 beforeEach(module('serviceModule'));
 beforeEach(module('loginModule'));
 beforeEach(module(‘appModule'));

 beforeEach(inject(function ($rootScope, $controller, $httpBackend, loginService) {
  scope = $rootScope.$new();
  httpBackend = $httpBackend;
  loginService = _loginService_;
  loginController = $controller('loginController', {
   $scope: scope
  });
 }));
it('Making a login request to the server', function () {

   scope.userName = 'sampleuser';
   scope.password = 'password';
     httpBackend.whenPOST('http://localhost/service/login')
      .respond(200, {
       "success": true
      });

     afterEach(function () {
      httpBackend.verifyNoOutstandingExpectation();
      httpBackend.verifyNoOutstandingRequest();
     });

     scope.$apply(function () {
      scope.Login();
     });

   httpBackend.flush();
   expect(scope.responseData.success).toBe(true);

  });
});

scope.responseData is the object that stores the response data in the controller.

Aucun commentaire:

Enregistrer un commentaire