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

Test a callback method's functionality in Jasmine

本文关键字:方法 功能 回调 测试 Jasmine      更新时间:2023-09-26

我有一个服务如下。

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

使用上述参数的控制器之一:

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

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

我建议您对服务和控制器分别进行测试。如果要测试是否分配了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");
       }
  )
});