簡體   English   中英

TypeError:parsed在angularjs服務單元測試中未定義

[英]TypeError: parsed is undefined on angularjs service unit test

我正在嘗試對使用$ http的服務進行單元測試。 我正在使用Jasmine並且我繼續收到此錯誤:

TypeError:解析在angular.js中未定義(第13737行)

這就是我的服務:

angular.module('myapp.services', [])
.factory('inviteService', ['$rootScope', '$http', function($rootScope, $http) {
    var inviteService = {
        token: '',

        getInvite: function(callback, errorCallback) {
            $http.get('/invites/' + this.token + '/get-invite')

            .success(function(data) {
                callback(data);
            })

            .error(function(data, status, headers, config) {
                errorCallback(status);
            });
        }
    };

    return inviteService;
}]);

這是我的測試看起來像:

describe ('Invite Service', function () {
  var $httpBackend, inviteService, authRequestHandler;

  var token = '1123581321';

  beforeEach(module('myapp.services'));

  beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get('$httpBackend');
    authRequestHandler = $httpBackend.when('/invites/' + token + '/get-invite').respond({userId: 'userX'}, {'A-Token': 'xxx'});
    inviteService = $injector.get('inviteService');
  }));

  afterEach (function () {
    $httpBackend.verifyNoOutstandingExpectation ();
    $httpBackend.verifyNoOutstandingRequest ();
  });

  describe ('getInvite', function () {
    beforeEach(function () {
      inviteService.token = token;
    });

    it ('should return the invite', function () {
      $httpBackend.expectGET('/invites/' + token + '/get-invite');
      inviteService.getInvite();
      $httpBackend.flush();
    });
  });
});

我對基於angularjs的應用程序的單元測試非常陌生,我在angularjs文檔中使用了這個例子

https://docs.angularjs.org/api/ngMock/service/ $ httpBackend

我不確定我可能缺少什么,我已經嘗試了不同的東西,我總是得到同樣的錯誤,任何幫助將不勝感激。

parsed變量是來自相關服務的URL。 由於以下原因之一,它undefined

  • 網址格式錯誤
  • $ http.get未被調用
  • token未定義
  • sucesserror回調沒有data
  • .respond沒有被調用
  • .respond不包含響應對象作為參數

例如:

 describe('simple test', test);

 function test()
   {
   it('should call inviteService and pass mock data', foo);

   function foo() 
     {
     module('myapp.services');
     inject(myServiceTest);

     function myServiceTest(inviteService, $httpBackend)
       {
       $httpBackend.expect('GET', /.*/).respond(200, 'bar');

       function callback(){};

       inviteService.getInvite.token = '1123581321';
       inviteService.getInvite(callback, callback);

       $httpBackend.flush();

       expect(callback).toHaveBeenCalledOnce();
       }
     }
   }

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM