在我的 Controller 中,我有:
$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
有一个永远不会在单元测试中得到解决的 promise 。如何模拟 CompanyService
返回的 promise 或绕过它?
最佳答案
使用 Jasmine 中的 createSpyObj
方法简单地模拟调用:
describe('one test', function(){
var deferred, CompanyService, $scope;
beforeEach(inject(function ($q, $rootScope, $controller) {
params = {
$scope: $rootScope.$new(),
CompanyService = jasmine.createSpyObj('CompanyService', ['initialized'])
}
params.CompanyService.initialized.andCallFake(function () {
deferred = $q.defer();
return deferred.promise; //will fake to return a promise, in order to reach it inside the test
});
$controller('YourController', params);
});
it('my test', function(){
deferred.resolve({}); //empty object returned for the sample but you can set what you need to be returned
$scope.$digest(); //important in order to resolve the promise
//at this time, the promise is resolved! so your logic to test can be placed here
});
});
关于javascript - 如何对依赖于 Promise 的 AngularJS Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895684/