Question

I am just starting to use sinon library in jasmine tests and I am unable to get the expected behavior on the stub. It fails to report that the function was called, even though when I debug, I can see it being called. Probably I am setting up the stub incorrectly. I tried also "called" instead of "calledOnce" just to make sure that is it not number of calls issue.

Here is the sut:

(function(){

angular.module('app', []);

      var serviceId = "inSearchViewModel";
      angular.module('app').factory(serviceId,[inSearchViewModel])

      function inSearchViewModel()
     {
         var vm = {
         isSearchCriteriaValid : isSearchCriteriaValid,
         searchAttempted: false,
         searchCompleted: false,
         performSearch: performSearch
        }

        return vm;

        function isSearchCriteriaValid()
        {
           return true;
        }

        function performSearch()
        {
          vm.searchAttempted = true;

          if (isSearchCriteriaValid())
          {
            search()
         }
        }

        function search()
        {
            vm.searchCompleted = true;
         }
    }
    })();

Here is my test:

  describe("inSearchViewModel", function () {

    beforeEach(module('app'));
    beforeEach(function () {
        inject(function ($injector) {
            inSearchViewModel = $injector.get('inSearchViewModel');
        });

        var sut = inSearchViewModel;
    });

     describe('performSearch() ', function () { 

        it('when search criteria is not valid performs no search',function() {         

            var isSearchCriteriaValidStub = sinon.stub(sut,"isSearchCriteriaValid").returns(false);

            sut.performSearch();

            expect(sut.searchAttempted).toBe(true);
            expect(sut.searchCompleted).toBe(false);

            sinon.assert.calledOnce(isSearchCriteriaValidStub);
            sinon.assert.called(isSearchCriteriaValidStub);

        });
    });
});
Was it helpful?

Solution

After reviewing the code I found where the error occurs, and only after creating a complete contrived example for SO :). Call to isSearchCriteriaValid() should actually go through instance of vm. So it should be vm.isSearchCriteriaValid().

function performSearch()
{
  vm.searchAttempted = true;

  //if (isSearchCriteriaValid())
   if (vm.isSearchCriteriaValid())
  {
      search()
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top