1

我有这个简单的控制器,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');
  });
});
4

1 回答 1

3

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

您正在尝试从控制器中读取内容,但它没有在测试中的任何地方定义,我猜您指的是模块。

这就是我要做的事情+小提琴

//--- 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');
    });
});

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

于 2014-03-10T05:26:46.523 回答