R4nc1d
R4nc1d

Reputation: 3113

Jasmine - Spying on a methods

I want to test a service call loginUser inside a LoginController. Now it is fine if loginUser is global method.

but i am trying to test it after the login button was click.

Controller

$scope.login = function () {

        UtilsFactory.showLoader();
        LoginService.loginUser($scope.data.username, $scope.data.password, false).success(function (data) {
            UtilsFactory.hideLoader();

            if ($scope.loginSuccessfull(data)) {
                $location.path('/tab');
            } else {
                UtilsFactory.hideLoader();
                UtilsFactory.popup('Login failed!', data.Message);
            }

        }).error(function (data) {
            UtilsFactory.hideLoader();
            UtilsFactory.popup('Login failed!', 'Login credentials failed!');
        });
    }

Tests

describe("Unit: Login Controllers", function () { var $rootScope, $scope, $controller, LoginService;

    // load the controller's module
    beforeEach(module('starter'));

    beforeEach(inject(function (_$rootScope_, _$controller_, _LoginService_) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $controller = _$controller_;
        LoginService = _LoginService_;

        $controller('LoginController', {
            '$rootScope': $rootScope,
            '$scope': $scope,
            'LoginService': LoginService
        });

    }));

//Success
    it("should call the login method on the LoginController", function () {
        spyOn($scope, "login");
        $scope.login();
        expect($scope.login).toHaveBeenCalled();
    });


//Fails
    it("calls the loginUser() function", function () {

        spyOn(LoginService, "loginUser");
        spyOn($scope, "login");
        $scope.login();
        expect(LoginService.loginUser).toHaveBeenCalled();
    });
});

and the error i am getting is

calls the loginUser() function
Error: Expected a spy, but got undefined.

I understand why i am getting it, just don't know how to fix it.

Upvotes: 0

Views: 433

Answers (1)

Michael Radionov
Michael Radionov

Reputation: 13309

spyOn does no return a spy, but replaces a method of your object with a spy. So your spy variable gets undefined, because again spyOn does not return anything, and that's why you get this error. Instead, you should pass a method which is being replaced by a spy to expect:

// replaces method 'loginUser' in LoginService object
spyOn(LoginService, 'loginUser'); 

// ...

// pass a spy to expect
expect(LoginService.loginUser).toHaveBeenCalled();

Upvotes: 1

Related Questions