我正在与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 :(得分:0)
尝试$ rootScope。$ digest(); //解决/拒绝承诺
it('should call myService service and populate the array', function(){
$rootScope.$apply();
expect(scope.list1.length).toBeGreaterThan(0);
});
你需要附上list1Available&& scope.list2可以使用$ 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.list1Available
expect(scope.list1Available).toEqual(false);