1

I am new to jasmine testing and I could not get a solid picture about how I could unittest my controller. My controller does some assignments and I basically want test to do the following:

  1. Mock service that it calls.
  2. Mock data in scope.
  3. Test the behaviour of the particular method in controller.
  4. Verify that: service has been invoked once.
  5. Verify that: service was passed correct data.

I would need to have as complete as possible example how to write a test, and what declarations to use to mock the methods.

Controller method in question looks like this:

.controller('ProjectConfigurationCtrl', function($scope, $routeParams, InfraService, ProjectConfigurationService) {
  // some pre-init...

  $scope.clickUpdate = function() {
     if ($scope.projectData.Id === 0) {
       ProjectConfigurationService.save(angular.toJson($scope.projectData), function(project) {
      $scope.projectData = project;
      $scope.newproject = false;
      $scope.info = "Project " + project.ProjectName + " created successfully.";
        }, function() {
      $scope.info = "Project " + $scope.projectData.ProjectName + " can not be created: server error.";
      });
      } else {
        ProjectConfigurationService.update(angular.toJson($scope.projectData), function() {
        $scope.info = "Project " + $scope.projectData.ProjectName + " updated successfully.";
        }, function() {
        $scope.info = "Project " + $scope.projectData.ProjectName + " can not be updated: server error.";
  });
}

I want to see if ProjectConfigurationService.save/update was called once, and check what arrived to these calls as parameters. I want mocked service return information. After the call, I want to examine $scope.newproject, $scope.info etc. to see what is inside there.

onkami
  • 8,791
  • 17
  • 90
  • 176

1 Answers1

1

See answer in Angular Unit Testing on Controller using a Service - Breaking on Inject as a reference jasmine test. You can search around the web for more examples if needed.

I am pleased to see that your idea in what to "unit-test" is correct so keep going. The key thing is, you have to inject $controller which is a controller constructor service, allowing you to pass the mocked dependencies. In your case, in your "it" function you should have something like:

var projectConfigCtrl = $controller('ProjectConfigurationCtrl', // name of your controller
     /* mocked dependencies */ {$scope: <yourMockedScope, usually $rootScope.$new>,
                                $routeParams: <your mock>,
                                InfraService: <your mock service>,
                                ProjectConfigurationService: <your mock service>});
Community
  • 1
  • 1
ailveen
  • 583
  • 3
  • 14