无法测试服务器调用的控制器

问题描述 投票:1回答:1

我正在尝试编写一个代码来测试在我的控制器中完成的服务调用。我正在尝试对正在进行服务调用并带来数据的控制器中的特定功能进行单元测试。目前我正在尝试使用本地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'); 
 };

unit Testing.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
javascript angularjs karma-jasmine
1个回答
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();
    }); 
});
© www.soinside.com 2019 - 2024. All rights reserved.