Search code examples
angularjsangularjs-servicesinon

How to test a method which returns a promise in sinon?


I have the following controller:

app.controller('SearchVideosController',

function SearchVideosController($scope, videoRepository) {

  $scope.DoSearch(id, text) {

    // Do some work...

    videoRepository.getVideosForUserBasedOnSearchText(id,text)
                       .then(function(data){
                          // Do something with the data.
                       });

   };

};

My videoRepository.getVideosForUserBasedOnSearchText() method uses $q and I want to create stub to ensure that the call is made.

I tried :

 it("should have 3 searched videos", function(){
  ...
    mockVideoRepository.getVideosForUserBasedOnSearchText.returns([]);

but get .then() is undefined.

Not sure how to handle the then() call.


Solution

  • You would need to get hold of $q service instance and use $q.when to create a promise wrapped value:-

    mockVideoRepository.getVideosForUserBasedOnSearchText.returns($q.when([]));
    

    Also remember you would need to manually perform a digest cycle in your test before the expecation to evaluate the result of the getVideosForUserBasedOnSearchText call. Only when a digest cycle is invoked promise will be resolved in your test. You can do it by getting hold of scope, and perform $digest or $apply. Example:- rootScope.$apply()