Jasmine Angular单元测试:带外部变量的控制器

时间:2015-10-07 17:03:53

标签: angularjs unit-testing controller jasmine

我试图为控制器编写一个单元测试,该控制器使用在控制器外定义的$ scope.action变量。

controller( "MyController", [
    "$scope", "$window", "httpInterceptor",
    function($scope, Service1, Service2, $window, httpInterceptor) {
            $scope.init = function() { ... });
            $scope.action.cb.write = function() { ... };
            $scope.action.cb.read = function() { ... };
        }]
);

我的单元测试如下。

describe("The controller", function () {
    var $controller, $scope, httpInterceptor, window, httpBackend;

beforeEach(function() {
    inject(function(_httpInterceptor_, _$controller_, _$rootScope_, $httpBackend, $http) {
        $scope = _$rootScope_.$new();
        httpInterceptor = _httpInterceptor_;
        httpBackend = $httpBackend;
        window = {setTimeout: function() {}};
        $controller = _$controller_("MyController", {
            httpInterceptor: _httpInterceptor_, $scope: $scope, $window: window, $http: $http
        });})});
afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

describe("The init() method", function () {
    it("Init method", function () {
        $scope.$parent.action = {}
        $scope.init();
    });});});

我收到错误TypeError: Cannot read property "cb" from undefined。我很困惑为什么我得到这个错误,因为我试图只测试init函数。我最初尝试将$scope.$parent.action = {}模仿$scope.action = {}无效。

感谢。

2 个答案:

答案 0 :(得分:1)

因为在控制器获得"实例化"时引用了$scope.action,所以在测试中分配它实际上太晚了,因为describe / it块在beforeEach / inject块之后运行完了。你应该在你的注入中初始化它。

inject(function(_httpInterceptor_, _$controller_, _$rootScope_, $httpBackend, $http) {
    $scope = _$rootScope_.$new();
    $scope.action = {};

答案 1 :(得分:1)

在将$scope属性注入测试中的控制器之前定义$scope = _$rootScope_.$new(); $scope.action = {'cb': {}}; 属性:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Sheet("Sheet2").AutoFilter.ApplyFilter
    ActiveWorkbook.Save
    ThisWorkbook.Saved = True
End Sub