简体   繁体   中英

How to create tests with Jasmine for services and controllers for Angular.js?

I have Angular services and controllers that work fine, and I am not able to create tests for them correctly. I've been looking everywhere for a solution.

My controller:

angular.module('wideCmsAngularApp').controller('UserListCtrl', [
  '$scope',
  'userService',
  '$routeParams',
  function ($scope, userService, $routeParams) {

    // Get quantity and offset from url. Format: /user/list/10/0
    var quantity = typeof $routeParams.quantity !== 'undefined' ? $routeParams.quantity : 10;
    var offset   = typeof $routeParams.offset !== 'undefined' ? $routeParams.offset : 0;

    $scope.users = userService.query({
      'param1' : quantity,
      'param2' : offset
    });

  }
]);

The service used by it:

angular.module('wideCmsAngularApp').factory('userService', [
  '$resource',
  function ($resource) {

    return $resource('http://localhost:1337/api/v1/user/:param1/:param2', {}, {
      'get'    : {method : 'GET'},
      'save'   : {method : 'POST'},
      'query'  : {method : 'GET', isArray:true},
      'remove' : {method : 'DELETE'},
      'delete' : {method : 'DELETE'}
    });
  }
]);

The test for the controller:

describe('UserListCtrl', function() {

  beforeEach(module('wideCmsAngularApp'));

  var $controller;
  var $rootScope;
  var userService;

  beforeEach(inject(function(_$rootScope_, _$controller_, _userService_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
    $rootScope  = _$rootScope_;
    userService = _userService_;
  }));

  describe('when asking for a list of users', function() {
    it('should return 4 users', function() {

      var $scope = [];
      var controller = $controller('UserListCtrl', {
        '$scope': $scope,
        'userService': userService,
        '$routeParams': {
          'quantity' : 10,
          'offset'   : 0
        }
      });

      expect($scope.users.length).toBe(4);
    });
  });
});

The result (should return an array of users with 4 users, but is always empty):

PhantomJS 1.9.8 (Mac OS X) UserListCtrl when asking for a list of users should return 4 users FAILED
    Expected 0 to be 4.
        at /somewhere/test/spec/controllers/user/list.js:31

What am I missing here?

--UPDATE--

I was able to do it this way, although that's not what I would really like, since I would prefer the actual API request to be made. Is that possible, or do I have to live with fake responses?

New UserListCtr test, using $httpBackend:

var $httpBackend;
var $controller;
var $rootScope;
var userService;

describe('UserListCtrl', function() {

  beforeEach(module('wideCmsAngularApp'));

  beforeEach(inject(function ($injector) {

    var uri = 'http://localhost:1337/api/v1/user/10/0';
    var users = [
      {
        "id": "555daff2862a513508a52ecd",
        "name": "Gru"
      },
      {
        "id": "555daff3862a513508a52ece",
        "name": "Kevin"
      },
      {
        "id": "555daff3862a513508a52ece",
        "name": "Ed"
      },
      {
        "id": "555daff3862a513508a52ece",
        "name": "Tim"
      }
    ];

    httpBackend = $injector.get('$httpBackend');
    httpBackend.whenGET(uri).respond(users)

    $controller = $injector.get('$controller');
    $rootScope  = $injector.get('$rootScope');
    userService = $injector.get('userService');
  }));

  describe('when asking for a list of users', function() {
    it('should return 4 users', function() {

      var $scope = $rootScope.$new();
      var controller = $controller('UserListCtrl', {
        '$scope': $scope,
        'userService': userService,
        '$routeParams': {
          'quantity' : 10,
          'offset'   : 0
        }
      });

      httpBackend.flush();

      expect($scope.users.length).toBe(4);
    });
  });
});

You should go for end to end testing using protractor. if you want a real response coming from server instead of using httpbackend.

    angular.module('wideCmsAngularApp').factory('userService', [
      '$resource',
      function ($resource) {

        return $resource('http://localhost:1337/api/v1/user/:param1/:param2', {}, {
          'get'    : {method : 'GET'},
          'save'   : {method : 'POST'},
          'query'  : {method : 'GET', isArray:true},
          'remove' : {method : 'DELETE'},
          'delete' : {method : 'DELETE'}
        });
      }
    ]);

if we take a look at line number 4 $resource('http://localhost:1337/api/v1/:param1/:param2', {}, { you'll see that you've got three parameters that you're passing, the URL, the paramDefaults and the actions, you aren't passing any paramDefaults. indicated by the {} right after :param2', Your paramDefaults have been set in the controller though;

$scope.users = userService.query({
      'param1' : quantity,
      'param2' : offset
    });

You need to pass these into $resource

$resource Docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM