2016-01-07 60 views
0

我正在用Karma和Jasmine编写我的第一个Angular app测试。

我有这个功能的控制器:

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 

就像我说的这些是我的第一次测试,所以任何帮助表示赞赏!

回答

0

尝试$ rootScope。$ digest(); //解决/拒绝承诺

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

您需要list1Available & & scope.list2Available附加到$范围,使他们能够在控制器的外部访问。

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.list1Available

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