2016-11-22 82 views
-1

我正在爲現有的AngularJS應用程序編寫單元測試。這項服務只有四種方法。我能夠讓FollowUpList工作,但是refresh()不起作用,這是一個非常簡單的方法。在Angular JS服務單元測試中未定義的方法

刷新方法應該簡單地設置deferredGetFollowUpList = null並在我的測試中返回true。

我得到的錯誤是:TypeError: Cannot read property 'then' of undefined,所以我的刷新方法是未定義的。爲什麼會這樣?由於

服務

(function() { 
    "use strict"; 

    angular 
     .module("all.patient.details") 
     .factory("followUpListService", ["$rootScope", "$http", "userContext", "$q", "$uibModal", "htmlBaseUrl", FollowUpListService]); 

    function FollowUpListService($rootScope, $http, userContext, $q, $uibModal, htmlBaseUrl) { 
     var deferredGetFollowUpList = null; 

     return { 
     getFollowUpList: getFollowUpList, 
     displayModal: displayModal, 
     refresh: refresh, 
     save: save 
     } 

     function refresh() { 
     deferredGetFollowUpList = null; 
     } 
    } 
})(); 

單元測試

describe("followUpListService", function() { 

    beforeEach(module("all.patient.details")); 
    var followUpListService = {}; 
    var $httpBackend; 
    var htmlBaseUrlMock; 
    var returnedFollowUpListData; 
    var deferredGetFollowUpList; 
    var $rootScope; 
    var $q; 
    var $uibModal; 

    beforeEach(function() { 

     htmlBaseUrlMock = { format: function() { } };  

     module(function ($provide) { 
      $provide.value("htmlBaseUrl", htmlBaseUrlMock); 
     }); 

     inject(function (_$rootScope_, _$httpBackend_, _$q_, _$uibModal_, _followUpListService_) { 
      $rootScope = _$rootScope_; 
      $httpBackend = _$httpBackend_; 
      $q = _$q_; 
      $uibModal = _$uibModal_; 
      followUpListService = _followUpListService_;   
     }); 

    }); 

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

    it("calls refresh()", function() { 

     followUpListService.refresh() 
     .then(function (data) { 
      deferredGetFollowUpList = data; 
     }); 

     expect(deferredGetFollowUpList).toBe(null); 
    }); 
+0

刷新的功能回報'undefined'。未定義不具有屬性 - 因此,這是錯誤的根源。你需要從'refresh()'方法返回promise。 –

回答

0

由於deferredGetFollowUpList是服務水平的變量,你可以寫你的測試爲 -

followUpListService.deferredGetFollowUpList = data; //Any Mock Data 
followUpListService.refresh(); 
expect(followUpListService.deferredGetFollowUpList).toBe(null); 
相關問題