不调用定义的服务方法,而是调用实际服务

时间:2015-08-07 20:52:45

标签: angularjs unit-testing jasmine

我关注this video tutorial,其来源为here

我正在尝试应用this test

这是我的测试

describe("InStudentController", function () {
    beforeEach(module("eucngts"));
    var inStudentsController;
    var MyInStudentsService;

    var $scope;
    var $q;
    var deferred;
    beforeEach(function () {

        MyInStudentsService =
            {
                getInStudents: function () {
                    deferred = $q.defer();
                    return deferred.promise;
                }
            };
    });

    beforeEach(inject(function ($controller, $rootScope, _$q_) {
        $q = _$q_; 
        $scope = $rootScope.$new();
        inStudentsController = $controller('InStudentsController', {
            service: MyInStudentsService 
        });
    }));
    it("should request list of inStudents", function () {
        spyOn(MyInStudentsService, "getInStudents").and.callThrough();
        inStudentsController.getPage(); // <-- HERE
        //deferred.resolve();
        $scope.$root.$digest();  
        expect(MyInStudentsService.getInStudents).toHaveBeenCalled();
    });
});

以下是相关的控制器代码:

            InStudentsController.prototype.getPage = function (criteria) {
                var self = this;
                self.showGrid = true;
                self.service.getInStudents();  

            };

当我在测试中调用 getPage()时,它会调用实际服务方法,而不是在测试中定义。

我做错了什么?

修改

我在我的控制器中没有使用范围这里是生成的代码(我使用的是typescript):

function InStudentsController (service) {
        var self = this;
        self.service = service; 
    }

InStudentsController.$inject = ['InStudentsService'];
angular.module("eucngts").controller("InStudentsController", InStudentsController);

2 个答案:

答案 0 :(得分:1)

根据您的最新更新,显然在测试中使用了依赖关系的名称。它必须是InStudentsService而不是service。当使用控制器构造函数的$inject属性时,只有该名称很重要,而不是函数中的形式参数名称。这使缩小成为可能

  inStudentsController = $controller('InStudentsController', {
        InStudentsService: MyInStudentsService 
    });

答案 1 :(得分:0)

目前您还没有将示波器注入控制器。我想这个:

$scope = $rootScope.$new();
inStudentsController = $controller('InStudentsController', {
    service: MyInStudentsService 
});

应该是这样的:

$scope = $rootScope.$new();
$scope.service = MyInStudentsService
inStudentsController = $controller('InStudentsController', {
    $scope: $scope
});

但在服务范围内传递服务似乎很奇怪。相反,你应该声明控制器是这样的:

angular.module('myApp')
  .controller('InStudentsController', function ($scope, InStudentsService) {
...
  });

然后服务会像这样注入:

$scope = $rootScope.$new();
inStudentsController = $controller('InStudentsController', {
    $scope: $scope,
    InStudentsService: MyInStudentsService
});