Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve 'undefined is not a function' in my case

I am trying to create unit test for my controller.

I have something like

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

In my factory file

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;
    }
]);

My unit test

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….
        });
    });
})

I am stuck at the error message and I am not sure what to do for the factory test. I am not sure how I can test the getProduct method for my service in the controller.

like image 204
BonJon Avatar asked Feb 10 '23 07:02

BonJon


1 Answers

In the unit test, you need to create a new scope object, not just an empty object literal. And you also need to inject a testFactory object when instantiating your controller. Off the top of my head, something like this:

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
        });
    });
})
like image 74
Travis Collins Avatar answered Feb 12 '23 21:02

Travis Collins