mardi 28 avril 2015

How to solve 'undefind 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. Can anyone help me about it? Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire