为什么sinon存根不按预期工作?

时间:2013-12-11 21:10:38

标签: angularjs jasmine sinon

我刚开始在茉莉花测试中使用sinon库,我无法在存根上获得预期的行为。它无法报告该函数被调用,即使在我调试时,我可以看到它被调用。可能我错误地设置了存根。我还尝试“调用”而不是“calledOnce”只是为了确保它不是调用次数问题。

这是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;
         }
    }
    })();

这是我的测试:

  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);

        });
    });
});

1 个答案:

答案 0 :(得分:0)

在查看代码后,我发现错误发生的地方,并且只在为SO创建一个完整的设计示例后:)。调用isSearchCriteriaValid()实际应该通过vm的实例。所以它应该是vm.isSearchCriteriaValid()。

function performSearch()
{
  vm.searchAttempted = true;

  //if (isSearchCriteriaValid())
   if (vm.isSearchCriteriaValid())
  {
      search()
   }
}