SpyOn returns Expected a spy, but got Function

10,591

First, you defined your spy after you called return, so that code will never be run. Second, define your spy in your test, not in beforeEach.

var createController,service scope;
beforeEach(inject(function($rootScope, $controller,$injector){
    service = $injector.get('service ');
    scope = $rootScope.$new();
    createController = function() {
        return $controller('controller', {
            '$scope': scope
        });    
    };
}));

describe('test if service is called', function() {
    it('should call the service', function() {
        var controller=createController();
        spyOn(service , ['redirect']).andCallThrough();
        scope.goToPage();
        expect(service.redirect).toHaveBeenCalled();
    });
});
Share:
10,591
Kratos
Author by

Kratos

Updated on June 04, 2022

Comments

  • Kratos
    Kratos almost 2 years

    I am testing a controller that calls a service(through the goToPage function) in order to redirect using the spyOn. It's simple but I am getting "Expected a spy, but got Function." error. What am I doing wrong? This is my Spec:

    var createController,service scope;
    beforeEach(inject(function($rootScope, $controller,$injector){
        service = $injector.get('service ');
        scope = $rootScope.$new();
        createController = function() {
            return $controller('controller', {
                '$scope': scope
            });
            spyOn(service , ['redirect']).andCallThrough();
        };
    }));
    
    describe('test if service is called', function() {
        it('should call the service', function() {
            var controller=createController();
            scope.goToPage();
            expect(service.redirect).toHaveBeenCalled();
        });
    });
    

    });