无法测试服务器呼叫的控制器

时间:2017-12-18 15:53:46

标签: javascript angularjs karma-jasmine

我正在尝试编写一个代码来测试在我的控制器中完成的服务调用。我正在尝试对正在进行服务调用并带来数据的控制器中的特定功能进行单元测试。目前我正在尝试使用本地json,但它实际上会进行服务调用。

我知道首先我创建了一个间谍对象,但我得到的错误是" TypeError:jasmine.CreateSpyObj不是一个函数" ,我是单元测试的新手。我无法创建一个spyobject,因此无法继续进行。请使用我的代码,请求您帮助我。

此外,我不确定一旦我成功创建spyObject,我究竟要做什么,我实际上想测试我的服务是否受到了很好的打击而且我得到了服务的响应。

请帮助我,我现在很多天都在这里苦苦挣扎。

服务代码:

//app is the module name
app.factory('appServices', ['$rootScope', '$http', function($rootScope, 
$http) {
var appServices = {};
appServices.getData = function(){
      return $http.get(scripts/services/data/unitTesting.json'); 
 };

unitTesting.json代码:

{
"name":"unit testing",
"countryCode": "EG",
"countryName": "Egypt",
"region": "Africa"
}

控制器代码:

getData: function(){
        appServices.getData().then(function(response) {
            if (response && response.data) {
                $scope.testVariable= response.data.name;
            }
        });
    },

单元测试代码:

  describe('myCtrl', function() {
      beforeEach(module('app'));

      var $controller;

      beforeEach(inject(function(_$controller_){
         $controller = _$controller_;
  }));

 describe('service call test', function() {
 var $http,$httpBackend,appServices,
 myService,$q,$rootScope,controller;

 var mockItem = 
       {
       "name":"unit testing",
       "countryCode": "EG",
       "countryName": "Egypt",
       "region": "Africa"
       }
 beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_, 
 _$rootScope_) {
   $http = _$http_;
   $httpBackend = _$httpBackend_; 
   appServices = appServices; 
   $rootScope = _$rootScope_;
   $q =_$q_;
   jasmine.spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
   controller = $controller('myCtrl', { $scope: $scope });
 }));
  it('Service call test ', function() {
  controller = $controller('myCtrl', { $scope: $rootScope.new() });
  controller.getData();
  expect(appServices.getData).toHaveBeenCalled();
 }); 
 });
 });

错误:

 TypeError: jasmine.spyOn is not a function

1 个答案:

答案 0 :(得分:0)

使用spyOn功能:

jasmine.spyOn(appServices, 'getData');

然后,您可以检查测试中的呼叫,如:

expect(appServices.getData).toHaveBeenCalled();

看看你如何编写规范,我是否可以建议其他一些更改来帮助你运行它:

var $rootScope,
    controller,
    $q;

beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_, _$rootScope_){
     $http = _$http_;
     $httpBackend = _$httpBackend_; 
     appServices= appServices;
     $rootScope = _$rootScope_;
     $q = _$q_;
     jasmine.spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
     controller = $controller('myCtrl', { $scope: $scope });
}));
describe('when fetching data in the controller', function(){
    it('should delegate the call to appServices.getData()', function() {
        controller = $controller('myCtrl', { $scope: $rootScope.new() });
        controller.getData();
        expect(appServices.getData).toHaveBeenCalled();
    }); 
});