在Jasmine中测试回调方法的功能

时间:2016-09-06 14:39:37

标签: javascript jasmine

我有以下服务。

InvService(...){
  this.getROItems = function(cb){
    $http.get('url').success(cb);  
  }  
}

使用上述控制器之一:

var roItems = [];  
InvService.getROItems(function(res){   
  roItems = res.lts.items;  
});

在Jasmine中,我想测试roItems是否从响应中分配了值。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

我建议您为服务和控制器分别进行测试。如果要测试roItems已分配,则需要测试控制器。然后,您可以模拟您的服务,因为它与控制器测试无关,并使其返回您想要的任何内容。你需要这样的东西:

describe('my awesome test', function() {

  it('my awesome test block',                           
       inject(function(InvService, $controller) {
              //This mocks your service with a fake implementation.
              //Note that I mocked before the controller initialization.
              spyOn(InvService, 'getROItems').and.callFake(function(cb){
                  var resultFake = {
                       lts: {
                           items: "whatever you want"
                       }
                  } 
                  cb(resultFake);
              });
              //This initializes your controller and it will use the mocked 
              //implementation of your service
              var myController = $controller("myControllerName");

              //Here we make the assertio
              expect(myController.roItems).toBe("whatever you want");
       }
  )
});