测试使用$ resource响应执行服务的控制器

时间:2016-03-23 21:48:08

标签: angularjs testing jasmine ngresource

我有一个使用服务的控制器,解析一个promise然后设置一个变量。 我想测试变量是否已设置,我该怎么做?

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()
   }
}])

控制器

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);
  });

});

1 个答案:

答案 0 :(得分:2)

模拟服务方法并返回一个promise,然后在需要时解析它。

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);
  });

});