2016-09-26 54 views
1

單元測試:遇到問題嘲諷承諾回報率來測試我的EMIT單元測試:遇到問題嘲諷承諾回報率來測試我的EMIT

我想看看是否EMIT得到的承諾回調調用。

這是我的代碼我測試:

"use strict"; 

angular.module("app.directives") 
    .directive("modalFilter", ["filterValidationService", function(filterValidationService) { 
     return { 
      restrict: "E", 
      scope: {}, 
      templateUrl: "templates/components/modal-filter.html", 
      link: function(scope) { 
       let defaultFilter = {"size": {"to": 0, "from": 0}}; 

       scope.clearFilter = function() { 
        scope.filter = defaultFilter; 
       }; 

       //New - requires unit test 
       scope.updateTable = function() { 
        const tab = "availabilities"; 
        const isFilter = scope.filter === defaultFilter ? false : true; 

        filterValidationService.validateSize(scope.filter.size) 
         .then(filterObj => { 
          scope.$emit("filter:cardData", filterObj, tab, isFilter); 
         }); 
       }; 

       scope.clearFilter(); 
      } 
     }; 
}]); 

這是我的單元測試:

"use strict"; 

describe("modal filter component:", function() { 
    var element; 
    var scope; 
    var mockData = {"size": {"to": 0, "from": 0}}; 
    var mockFilteredData = {"size": {"to": 900, "from": 100}}; 
    var filterValidationService; 

    beforeEach(angular.mock.module("eg.insight.services")); 
    beforeEach(angular.mock.module("eg.insight.directives")); 

    beforeEach(inject(function ($compile, $injector, $q, $rootScope, filterValidationService) { 
     var deferred = $q.defer(); 
     scope = $rootScope.$new(); 
     scope.filter = mockData; 
     filterValidationService = filterValidationService; 

     element = "<modal-filter></modal-filter>"; 
     element = $compile(element)(scope); 

     angular.element(document.body).append(element); 

     scope.$digest(); 
     scope = element.isolateScope(); 

     sinon.spy(scope, "$emit"); 

     sinon.stub(filterValidationService, "validateSize").returns(deferred.promise); 
    })); 

    it("should emit for filtered data when updateTable is called", function() { 
     scope.updateTable(); 
     expect(scope.$emit.calledWith("filter:cardData", mockData.size, "availabilities", false)).toEqual(true); 
    }); 
}); 

我使用angular1茉莉單元測試和興農。

我得到的錯誤是:「預期虛假等於真正的」

回答

1

我想這可能是因爲在這裏你會返回一個承諾

sinon.stub(filterValidationService, "validateSize").returns(deferred.promise);

,但你永遠解決承諾,所以.then()永遠不會被調用。

也許在變量中承諾並在您的it()方法中使用scope.UpdateTable()後解決。

+0

會是這樣的:deferred.resolved(mockData.size); – AngularM

+0

方法名稱爲'resolve' https://docs.angularjs.org/api/ng/service/$q您可能需要考慮在您的it()中添加deferred.promise.finally() '方法,然後你將執行'expect()'。 – Stephen