Error: Expected undefined to equal in karma

Error: Expected undefined to equal in karma

测试用例文件

describe('homeController', function() {
beforeEach(module('moduleInjectionApp'));

var $controller;
var $rootScope;
beforeEach(inject(function(_$controller_, _$rootScope_) {
    $controller = _$controller_('homeController', {'$scope': scope});
    $rootScope = _$rootScope_;
}));

describe('$scope.ID', function() {
    it('Check the scope object', function() {
        var $scope = {};
        expect($scope.ID).toEqual(5);
    });
  });
});

控制器文件

 angular.module('moduleInjectionApp').controller('homeController', homeController)
 homeController.$inject = ["$scope", "$rootScope", "$location"];
 function homeController($scope, $rootScope, $location) {
     console.log("entered homeController")
     $scope.ID = 5;
     $rootScope.loginObj = JSON.parse(localStorage.getItem('login_data'));
 }

错误

Error: Expected undefined to equal 5.
        at <Jasmine>
        at UserContext.<anonymous> (WebContent/test/home/homeSpec.js:14:31)
        at <Jasmine>

Chrome 75.0.3770 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) (0.036 secs / 0.012 secs) TOTAL: 1 FAILED, 0 SUCCESS

尝试

describe('homeController', function() {
    beforeEach(module('moduleInjectionApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
              $controller = _$controller_;
    }));

    describe('$scope.ID', function() {
        it('Check the scope object', function() {
            var $scope = {};
            var controller = $controller('homeController', { $scope: $scope });
            expect($scope.ID).toEqual(5);
        });
    });
});

当您声明 var $scope = {}; 时,您将始终得到 $scope.ID 未定义。你需要做

var $scope = { ID: 5}

无论如何,在单元测试中,您不会创建一些值,然后 expect 对其进行断言。您验证已定义或已修改的值。在这里你试图声明然后放置 expect (它总是会通过)