gpt4 book ai didi

javascript - 我如何对依赖于 promise 的 AngularJS Controller 进行单元测试?

转载 作者:行者123 更新时间:2023-11-29 17:10:42 26 4
gpt4 key购买 nike

在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com