Javascript 控制器$scope变量在jasmine测试中未定义

Javascript 控制器$scope变量在jasmine测试中未定义,javascript,angularjs,unit-testing,karma-jasmine,Javascript,Angularjs,Unit Testing,Karma Jasmine,我正在用Karma和Jasmine编写我的第一个Angular应用程序测试 我有一个具有此功能的控制器: function getMyLists() { getLists.getOne().then(function(listOne) { $scope.list1 = listOne[0]; list1Available = true; }); getLists.getTwo().then(function(listTwo) { $scope.list2 =

我正在用Karma和Jasmine编写我的第一个Angular应用程序测试

我有一个具有此功能的控制器:

function getMyLists() {
  getLists.getOne().then(function(listOne) {
    $scope.list1 = listOne[0];
    list1Available = true;
  });
  getLists.getTwo().then(function(listTwo) {
    $scope.list2 = listTwo;
    list2Available = true;
  });
}

getMyLists();
我在测试中模拟了这项服务

describe('MainCtrl', function () {

  var rootScope, scope, controller, myService;

  beforeEach(angular.mock.module('myApp'));

  beforeEach(inject(function($rootScope, $controller, $q) {
    rootScope = $rootScope;
    scope = $rootScope.$new();

    myService = {
      getOne: function(){
        // mock promise
        var deferred = $q.defer();
        deferred.resolve([
          {
            "one": 1
         },
         {
            "type": list
         }
        ]);
        return deferred.promise;
      },
      getTwo: function(){
        // mock promise
        var deferred = $q.defer();
        deferred.resolve([
          {
            "two": 2
         },
         {
            "type": list
         }
        ]);
        return deferred.promise;
      }
    }

    controller = $controller('MainCtrl', {
      $scope: scope,
      myService: myService
    });
  }));

  it('should call myService service and populate the array', function(){
    scope.$digest();
    expect(scope.list1.length).toBeGreaterThan(0);
  });

});
这很好,我有一个通过测试,因为我会期待。但是当我试着测试下面的例子时,我总是出错

expect(scope.list2.length).toBeGreaterThan(0);
Expected undefined to be greater than 0.

expect(list1Available).toEqual(false);
ReferenceError: Can't find variable: list1Available
就像我说的,这是我的第一次测试,所以非常感谢您的帮助

试试$rootScope.$digest()//解决/拒绝承诺

 it('should call myService service and populate the array', function(){
    $rootScope.$apply();
    expect(scope.list1.length).toBeGreaterThan(0);
  });
您需要将list1Available&&scope.list2Available附加到$scope,以便可以在控制器之外访问它们

function getMyLists() {
  getLists.getOne().then(function(listOne) {
    $scope.list1 = listOne[0];
    $scope.list1Available = true;
  });
  getLists.getTwo().then(function(listTwo) {
    $scope.list2 = listTwo;
    $scope.list2Available = true;
  });
}
您的测试需要测试scope.List1是否可用

expect(scope.list1Available).toEqual(false);