2015-02-23 37 views
2

嗨我想知道如果任何人都可以告訴我如何測試回調結果在模擬測試角和茉莉花2.我們有一個服務,只是返回一些數據的調用而像這樣:角然後回調在模擬茉莉花測試

var getStuff = function (id) { 
    return $http.get("url/" + id) 
       .then(function (response) { 
        return response.data; 
       }); 
     }; 

,並在我們的控制,我們稱這種服務在啓動時:

angular.module('controllers').controller("myController", ['$scope', 'service', function ($scope, service) { 

    var onGetStuff = function(data) { 
     //do something with the result here 
    } 

    $scope.getItems = function() { 
     service.getStuff(1).then(onGetStuff); 
    } 


    $scope.getItems(); 
}]); 

我然後運行我的測試(會後的代碼在一個時刻,而是調用onGetStuff從來沒有被稱爲,我似乎無法弄清楚爲什麼。以下是測試代碼:

//includes here 

describe('Controller: Applicant Controller', function() { 

    var controller, $q, $scope, mockService, deferred, $rootScope; 

    beforeEach(module("controllers")); 

beforeEach(function() { 
     mockService = { 
      getStuff: function (id) { 
       deferred = $q.defer(); 
       deferred.resolve({somestuff: 1}); 
       return deferred.promise; 
      } 
     }; 

     spyOn(mockService, 'getStuff').and.callThrough(); 
}); 

beforeEach(inject(function ($rootScope, $controller, _$q_) { 
     $scope = $rootScope.$new(); 
     $q = _$q_; 

     controller = $controller('myController', { 
      $scope: $scope, 
      service: mockService 
     }); 
})); 


    it("it should work", function() { 
     debugger; 
    }); 

}); 

如果我通過Chrome的調試步驟,模擬服務被調用,但在我的控制器中的「onGetStuff」通話不會被調用,任何人都可以找出原因?

謝謝 Mocksy。

回答

1

創建控制器後,您需要撥打$rootScope.$apply()才能運行任何then回調。

+0

thx男人,完全錯過了,儘管它在其他職位被提及。 – Mocksy 2015-02-24 09:03:10