2016-03-19 4 views
0

$ httpBackendバックエンドモックでジャスミンユニットテストを実行すると問題が発生します。私はサービスコールから返された値をテストしたいと思っています。それはサービスを呼び出してエンドポイントを打っていますが、メソッド自体からエラーが発生し続けます。これが機能するために私が何が欠けているのか分かりません。どんな助けでも本当に感謝しています。

//エラー

TypeError: 'undefined' is not an object (evaluating 'data[0].data') 

///ユニットテスト

describe("DataService", function() { 

     describe('testing service', function() { 
      var TheService, scope; 

      beforeEach(function() { 
       module(moduleName); 
       module('services'); 
      }); 

      beforeEach(inject(function($injector,$rootScope) { 
       TheService = $injector.get('TheService'); 
       scope=$rootScope.$new(); 
      })); 

      it('should have a method defined', function() { 
       expect(TheService.getStuff).toBeDefined(); 
      }); 

      it('should have a method defined', inject(function($httpBackend) { 

      var mock = { data: 'World' }; 


       $httpBackend.whenGET("/theurl/getStuff").respond({ data: 'World' }); 


       $httpBackend.expectGET("/theurl/getStuff"); 

       TheService.getStuff(); 

       scope.$digest(); 

       expect(TheService.getStuff).toEqual(mock); 

       $httpBackend.flush(); 
      })); 

     }); 

}); 

//サービス方法

function TheService($http, $q) { 
     var vm = this; 


     vm.getStuffs = null; 
     vm.getStuff = getStuff; 
     vm.theresponse = {}; 

     function getStuff() { 

      var deferred = $q.defer(); 

      $http({ 
       method: 'GET', 
       url: "/theurl/getStuff" 

      }).success(function(data){ 

       vm.theresponse = data[0].data 
       deferred.resolve(vm.theresponse); 

      }).error(function(){ 

       deferred.reject('An error occurred'); 

      }); 

      return deferred.promise; 
     } 
    } 

答えて

2

まあ、偽のエンドポイントが返されます

{ data: 'World' } 

しかし、サービスは

data[0].data 

データがオブジェクトでアクセスしようとします。配列ではありません。したがって、data[0]は未定義です。正常に動作するサービスコードの場合

、あなたはまた、

[{ data: 'World' }] 

のようなものを返す必要があり、あなたのコードは、約束のアンチパターンを使用し、成功とエラーコールバックを非推奨。より良い代替方法については、http://blog.ninja-squad.com/2015/05/28/angularjs-promises/をお読みください。

+0

ありがとう@JB。私はそれを逃したとは信じられません。 – Jimi