0

I want to perform unit test on the if else statement so that the branch section of the code coverage gives good result.I am not getting the idea as in what exactly should be tested in the code below

Controller.js

(function () {
    "use strict";

    angular
        .module("app.login")
        .controller("LoginController", LoginController);

    LoginController.$inject = ["$scope", "$http", "$state", "$rootScope", "logger", "$location"];

    /**
     * @ngdoc controller
     * @name app.login.controller
     * @memberof app.login
     * @summary
     *  This is the controller for the login module
     *
     * @param {Object} $scope
     * @param {Object} $http
     * @param {Object} $state
     * @param {Object} $rootScope
     * @param {Function} logger
     * @constructor
     */
    function LoginController ($scope, $http, $state, $rootScope, logger, $location) {

        var vm = this;
        this.cancel = $scope.$dismiss;

        logger.info("Started LoginController");

        /**
         * login function
         *
         * @memberof app.login.controller
         */
        this.login = function () {
            if ($scope._username == "admin" && $scope._password == "password") {
                $state.go("main.login.success");
            } else {
                logger.error("Login Unsuccessful");
            }
        };

    }
})();

testing.js

describe("LoginController", function () {
    var $scope;
    var controller;
    var logger;
    var $cookies;
    var temp;

    beforeEach(module("app.login"));

    beforeEach(inject(function ($controller, _$rootScope_, _logger_, _$cookies_) {
        $scope = _$rootScope_.$new();

        controller = $controller("LoginController", {
            $scope: $scope,
            logger: _logger_

        });

        $scope.$digest();
    }));


it("admin should be the username", function () {
        $scope._username = "admin";
        expect($scope._username).toEqual("admin");

    });


    it("is username is admin", function () {

        expect(controller.login).toBe(true);
    });

I tried both but it doesnt cover the if-else branch yet. Can anyone please point out what am i missing in the code above. Thanks!

user2128
  • 590
  • 2
  • 13
  • 35

1 Answers1

0

Write your testcases as written below

it("admin should be the username", function () {
    $scope._username = "admin";
    $scope._password == "password";
     spyOn($state, 'go');
    controller.login();
    expect($state.go).toHaveBeenCalledWith('main.login.success');

});

it("should log error if username or password is incorrect", function () {
    $scope._username = "admin";
    $scope._password == "tests";
     spyOn(logger, 'error');
    controller.login();
    expect(logger.error).toHaveBeenCalledWith('Login Unsuccessful');

});

You first have to spy on the method which you want to watch and make expectation.

ankur kushwaha
  • 458
  • 3
  • 9