简体   繁体   English

如何使用Jasmine为Angular.js的服务和控制器创建测试?

[英]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. 我有Angular服务和控制器工作正常,我无法正确地为它们创建测试。 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): 结果(应返回具有4个用户的用户数组,但始终为空):

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-- --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. 我能够这样做,虽然这不是我真正想要的,因为我更喜欢实际的API请求。 Is that possible, or do I have to live with fake responses? 这是可能的,还是我必须忍受假的回应?

New UserListCtr test, using $httpBackend: 新的UserListCtr测试,使用$ 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. 如果你想要一个真正的响应来自服务器而不是使用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; 如果我们看看第4行$resource('http://localhost:1337/api/v1/:param1/:param2', {}, {你会看到你有三个参数'重新传递,URL,paramDefaults和动作,你没有传递任何paramDefaults。由{}后面指示:param2',你的paramDefaults已经在控制器中设置了;

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

You need to pass these into $resource 您需要将这些传递到$resource

$resource Docs $ resource文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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