控制器角度的单元测试

时间:2014-03-09 16:48:38

标签: angularjs unit-testing controller karma-runner karma-jasmine

我有这个简单的控制器,UserService是一个返回JSON的服务

"use strict";

angular.module("controllers").controller('profileCtrl', ["$scope", "UserService", 
    function ($scope, UserService) {
       $scope.current_user = UserService.details(0);
    }
]);

我无法进行测试。不过这是我的尝试

'use strict';

describe('profileCtrl', function () {
  var scope, ctrl;

  beforeEach(angular.mock.module('controllers'), function($provide){
    $provide.value("UserService", {
      details: function(num) { return "sdfsdf"; }
    });
  });

  it('should have a LoginCtrl controller', function() {
    expect(controllers.profileCtrl).toBeDefined();
  });

  beforeEach(angular.mock.inject(function($rootScope, $controller){
    scope = $rootScope.$new();
    $controller('profileCtrl', {$scope: scope});
  }));

  it('should fetch list of users', function(){
    expect(controllers.scope.current_user.length).toBe(6);
    expect(controllers.scope.current_user).toBe('sdfsdf');
  });
});

1 个答案:

答案 0 :(得分:3)

$ controller的用法是正确的,这是实例化单元测试控制器的方法。您可以在$ controller调用中模拟它直接获得的UserService实例。 您应该使用它的返回值 - 这是您要测试的控制器的实例。

你试图从控制器读取东西,但是在测试的任何地方都没有定义,我想你是指模块。

这就是我要做的事情+ fiddle

//--- CODE --------------------------
angular.module('controllers', []).controller('profileCtrl', ["$scope", "UserService",

function ($scope, UserService) {
    $scope.current_user = UserService.details(0);
}]);

// --- SPECS -------------------------

describe('profileCtrl', function () {
    var scope, ctrl, userServiceMock;

    beforeEach(function () {
        userServiceMock = jasmine.createSpyObj('UserService', ['details']);
        userServiceMock.details.andReturn('sdfsdf');
        angular.mock.module('controllers');
        angular.mock.inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            ctrl = $controller('profileCtrl', {
                $scope: scope,
                UserService: userServiceMock
            });
        });
    });

    it('should have a LoginCtrl controller', function () {
        expect(ctrl).toBeDefined();
    });

    it('should fetch list of users', function () {
        expect(scope.current_user).toBe('sdfsdf');
    });
});

欢迎您在线更改小提琴以了解它如何影响测试结果。