Angular $ scope方法测试

时间:2016-06-24 23:07:46

标签: angularjs unit-testing

我正在尝试测试是否已调用$ scope方法

我的控制员:

Range("J2", Cells(Cells(Rows.Count, "H").End(xlUp).Row, "J"))

和我的测试:

(function () {
    var app = angular.module('productsController',[]);
      app.controller('AddProductController', ['$scope',function ($scope) {
        $scope.test = function(){
          return true;   
        };
        $scope.test();
    }]);
})();

但是我收到了这个错误:

describe("Products Controller", function () {
    beforeEach(function () {
        module('productsController');
    });

    beforeEach(function () {
        var  createController, scope, rootScope;

    });
    describe('AddProductController', function () {
        beforeEach(function () {
            inject(function ($controller, _$rootScope_) {
                rootScope = _$rootScope_;
                scope = _$rootScope_.$new();
                createController = function () {
                    return $controller("AddProductController", {
                        $scope: scope,
                    });
                };
            });
        });

        it('should call test', function(){
            spyOn(scope, 'test');
            createController();
            scope.$apply()
            expect(scope.test).toHaveBeenCalled();
        })
    });
});

$ scope.test存在任何当我在浏览器中运行应用程序的方法被调用时,但如果falis whne测试,任何线索?

1 个答案:

答案 0 :(得分:0)

订购时可能存在一些问题,您可以尝试检查以下是否有效吗?

describe('AddProductController', function() {
    var  createController, scope, rootScope;

    beforeEach(function() {
        inject(function($controller, _$rootScope_) {
            rootScope = _$rootScope_;
            scope = _$rootScope_.$new();
            createController = function() {
                return $controller("AddProductController", {
                    $scope: scope,
                });
            };
        });
    });

    it('should call test', function() {
        createController(); // To create function test in the scope
        spyOn(scope, 'test');        
        createController(); // To execute test after spy is added.
        expect(scope.test).toHaveBeenCalled();
    })
});