【问题标题】:Testing a controller that execute a service with $resource response使用 $resource 响应测试执行服务的控制器
【发布时间】:2016-07-11 09:39:46
【问题描述】:

我有一个控制器,它使用一项服务,解决一个承诺,然后设置一个变量。 我想测试变量是否已设置,我该怎么做?

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


}])

控制器规格

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

});

【问题讨论】:

    标签: angularjs testing jasmine ngresource


    【解决方案1】:

    模拟服务方法并返回一个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);
      });
    
    });
    

    【讨论】:

    • 为什么thenmethod 被执行并且当我使用scope.$apply() 方法时我的值被更新了?是因为then方法中提供的功能还在等待$digest进程吗?如果有人帮助我理解这一点,我会非常感激。
    • 你需要调用 $scope.$apply() 来告诉 AngularJS 刚刚发生了一个异步事件。在这种情况下,您刚刚解决了一个承诺。
    猜你喜欢
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    相关资源
    最近更新 更多