我如何单元测试一个AngularJS控制器,它依赖于一个承诺? [英] How do I unit test an AngularJS controller that relies on a promise?
本文介绍了我如何单元测试一个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
返回的承诺或绕过它?
However, this never happens, because CompanyService
has a promise that never gets resolved in the unit test. How do I either mock the returned promise of CompanyService
or bypass it?
推荐答案
只需用 createSpyObj
方法从茉莉花嘲笑电话:
Simply mock the call using createSpyObj
method from Jasmine:
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
});
});
这篇关于我如何单元测试一个AngularJS控制器,它依赖于一个承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文