在我的例子中,如何解决'undefined不是一个函数'

Bon*_*Jon 4 javascript unit-testing angularjs

我正在尝试为我的控制器创建单元测试.

我有类似的东西

angular.module('myApp').controller('testCtrl', ['$scope', 'testFactory',
    function($scope, testFactory) {
        //I am getting the error when I ran Karma
        //TypeError: 'undefined' is not a function (evaluating  
        //'$scope.$watch')
        $scope.$watch(function(){
            return testFactory.returnItem; // watch the factory returned data
        }, function(newVal){
            console.log('call here')
        });
    }
]}
Run Code Online (Sandbox Code Playgroud)

在我的工厂文件中

angular.module('myApp').factory('testFactory', ['Product','$cookies','$q',
    function(Product ,$cookies, $q) {
        var service = {};
        service.getProduct = function() {
            var deferred = $q.defer();
            var that = this;
            Product.query({
                Id: 123,
            }, function(product) {           
                that.returnItem = product;
                deferred.resolve(product);
            });
            return deferred.promise;
        };
        return service;
    }
]);
Run Code Online (Sandbox Code Playgroud)

我的单元测试

describe('Test ', function () {
    beforeEach(module('myApp'));
    var $controller, testFactory;

    // Initialize the controller and a mock scope
    beforeEach(inject(function(_$controller_, _testFactory_){
        $controller = _$controller_;
        testFactory = _testFactory_;
    }));

    describe('Initial test', function() {
        it('should return data', function() {
            var $scope = {};
            var controlelr = $controller('testCtrl', {$scope:$scope});
            //not sure what to do next….
        });
    });
})
Run Code Online (Sandbox Code Playgroud)

我被困在错误信息中,我不知道该怎么做工厂测试.我不知道如何getProduct在控制器中测试我的服务方法.

Tra*_*ins 7

在单元测试中,您需要创建一个新的范围对象,而不仅仅是一个空的对象文字.并且还需要在实例化控制器时注入testFactory对象.在我的头顶,这样的事情:

describe('Test ', function () {
    beforeEach(module('myApp'));
    var $controller, testFactory, scope;

    // Initialize the controller and a mock scope
    beforeEach(inject(function(_$controller_, _$rootScope_, _testFactory_){
        $controller = _$controller_;
        $rootScope = _$rootScope_;
        testFactory = _testFactory_;
    }));

    scope = $rootScope.$new();

    describe('Initial test', function() {
        it('should return data', function() {
            var controller = $controller('testCtrl', {$scope:scope, testFactory:testFactory});
            // expect something here
        });
    });
})
Run Code Online (Sandbox Code Playgroud)