在我的控制,我有:如何单元测试依赖于承诺的AngularJS控制器?
$scope.index = function() {
CompanyService.initialized.then(function() {
var company_id = CompanyService.getCompany()._id;
LocationService.list(company_id, $routeParams.location_parent_id).then(function(response) {
if(response.data.status === 'ok') {
$scope.locations = response.data.locations;
$scope.current_location = response.data.location || null;
}
});
});
}
所以应该得到LocationService
和试验如下:
it('should get locations', function() {
$httpBackend.when('GET', '/api/v1/location/list').respond({status: 'ok', locations: ['loc1', 'loc2']})
$scope.index();
expect($scope.locations.length).toEqual(2);
但是,这永远不会发生,因为CompanyService
有一个承诺,永不在单元测试中得到解决。我如何嘲笑CompanyService
的退货承诺或绕过?
我得到'TypeError:'undefined'不是一个对象(评估'deferred.resolve')' – Shamoon
@Shamoon我做了一个更新,你使用的是完全相同的代码吗?如代码所示,确保在测试中可以访问deferred变量。 – Mik378
如何使用'$ injector'设置来完成此操作?我使用http://nathanleclaire.com/blog/2013/12/13/how-to-unit-test-controllers-in-angularjs-without-setting-your-hair-on-fire/作为基准我的测试 – Shamoon