if else语句angular js的单元测试

时间:2015-11-03 20:21:15

标签: angularjs unit-testing karma-runner karma-coverage

我想对if else语句执行单元测试,以便代码覆盖的分支部分给出了良好的结果。我没有得到关于在下面的代码中应该测试什么的想法

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

我试过了两个,但它还没有覆盖if-else分支。任何人都可以请指出我在上面的代码中缺少什么。谢谢!

1 个答案:

答案 0 :(得分:0)

编写您的测试用例,如下所示

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

});

首先,你必须监视你想要观察的方法,并期待。