本文介绍了测试以$资源响应执行服务控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用服务控制器,解决一个承诺,然后设置一个变量。
我想测试,如果变量已定,我怎么做呢?
Service.js
角
.module(MyModule的')
。服务('为MyService',['$资源',函数($资源){
变种R = $资源('/用户/:身份证',{ID:@ ID'});
this.post =功能(_user){
返程(新R(_user))。$保存()
}
}])
控制器
角
.module(MyModule的')
.controller('myCtrl',['为MyService,功能(为MyService){
VAR VM =这一点;
vm.value = 0;
vm.post =功能(_user){ MyService.post(_user)。然后(函数(){
vm.value = 1;
});
};
}])
controller_spec
描述(测试控制器,函数(){
beforeEach(模块('Mymodule中'));
beforeEach(注入(函数($控制器,为MyService){
this.ctrl = $控制器('myCtrl');
})) 它('后保存值是1,函数(){
this.ctrl.post({名称:'盘'}); //始终this.ctrl.value它等于0
期待(this.ctrl.value).toBeEqual(1);
});});
解决方案
嘲笑服务方法,并返回一个承诺,那么解决它,当你需要它。
描述(测试控制器,函数(){
VAR postDefer;
beforeEach(模块('Mymodule中'));
beforeEach(注(函数($控制器,为MyService,$ Q){
postDefer = $ .defer();
spyOn(为MyService,'后')and.returnValue(postDefer.promise)。
this.ctrl = $控制器('myCtrl',{为MyService:为MyService});
})) 它('后保存值是1,函数(){
this.ctrl.post({名称:'盘'}); postDefer.resolve(); 。范围$适用();
期待(this.ctrl.value).toBeEqual(1);
});});
I have a controller that use a service, resolve a promise and then set a variable.I want to test if the variable has been set, How I do this?
Service.js
angular
.module('myModule')
.service('MyService',['$resource',function($resource){
var r = $resource('/users/:id',{id:'@id'});
this.post = function(_user){
return (new r(_user)).$save()
}
}])
Controller
angular
.module('myModule')
.controller('myCtrl', ['MyService',function(MyService){
var vm = this;
vm.value = 0;
vm.post = function(_user){
MyService.post(_user).then(function(){
vm.value = 1;
});
};
}])
controller_spec
describe('Test Controller',function(){
beforeEach(module('myModule'));
beforeEach(inject(function($controller, MyService){
this.ctrl = $controller('myCtrl');
}))
it('after save value is 1',function(){
this.ctrl.post({name: 'chuck'});
//Always this.ctrl.value it's equal to 0
expect(this.ctrl.value).toBeEqual(1);
});
});
解决方案
mock the service method and return a promise, then resolve it when you need it.
describe('Test Controller',function(){
var postDefer;
beforeEach(module('myModule'));
beforeEach(inject(function($controller, MyService, $q){
postDefer = $.defer();
spyOn(MyService, 'post').and.returnValue(postDefer.promise);
this.ctrl = $controller('myCtrl', {MyService : MyService});
}))
it('after save value is 1',function(){
this.ctrl.post({name: 'chuck'});
postDefer.resolve();
scope.$apply();
expect(this.ctrl.value).toBeEqual(1);
});
});
这篇关于测试以$资源响应执行服务控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!