【发布时间】:2016-05-01 20:12:58
【问题描述】:
我对 Promise 不熟悉,并且似乎可以运行实际代码,但也尝试编写单元测试...
这是我的控制器:
appModule.controller('MyController', function($scope, myService, $timeout, mySecondService) {
$scope.accept = false;
$scope.loading = false;
$scope.text = 'Some text';
$scope.testCall = function() {
$scope.person = true;
$scope.text = '';
$scope.loading = true;
myService.getWeather()
.then(function(data) {
if (data.valid===true) {
$timeout(function(){
$scope.loading = false;
$scope.accept = true;
$timeout(function(){
$scope.customer.cart = false;
}, 1400);
}, 1500);
}
else {
$scope.person = false;
$scope.newMessage = mySecondService.getItem();
}
}, function(error) {
$scope.person = false;
$scope.newMessage = mySecondService.getItem();
});
}
});
控制器规格:
beforeEach(module('myApp'));
describe("MyController Tests", function() {
var scope;
var ctrl;
var customerInfo = {
"ID" : "212143513",
"firstName" : "Lewis",
"lastName" : "Noel"
};
beforeEach(inject(function($rootScope, $controller, myService) {
scope = $rootScope.$new();
rootScope = $rootScope;
mockMyService = myService;
ctrl = $controller('MyController', {$scope:scope, myService:mockMyService});
spyOn(scope, 'testCall').and.callThrough();
}));
it("On controller load, initialise variables", function() {
expect(scope.text).toEqual('Some text');
expect(scope.loading).toEqual(false);
expect(scope.accept).toEqual(false);
});
});
以上测试了 $scope 的初始化,但服务中没有任何内容...
这是我的服务:
appModule.factory('myService', function ($http, $q) {
return {
getWeather: function() {
return $http.get('/cart/customerCart/546546')
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
}
else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
};
});
【问题讨论】:
-
您需要隔离您正在测试的组件。如果您在控制器测试中而不是将原始服务分配给控制器,请传递一个模仿您服务的相同 API 但不发出任何请求的对象。或者使用 ngMockE2E 服务。无论如何,您需要手动调用 scope.$apply 来运行请求,因为模拟模块正在持有然后被执行
-
@Raulucco - 不是一个非常有用的评论。如果您查看我的第一个测试,您可以看到我隔离了控制器。一旦成功,接下来我将隔离服务。
标签: angularjs unit-testing jasmine karma-jasmine angular-services