Am working on Backbone application and i have to unit test it using sinon.js and Qunit.js. The scenario is i have one carView which extends baseview and the baseview extends backbone's view.

I have one function say buildFormUrl in the car view which returns a string. The string value is changed on the basis of user action.

Is it possible to make stub of buildFromUrl stub using sinon.stub and calling the stub function and then checking the return values?

Backbone Code Snippet:

             var CarSearchView = BaseView.extend({

             intitalize : function(){
               //some code
             },

             buildFormUrl: function(baseUrl){
             // process a different form url based on new/used selection
             var newUsedToggleValue = this.$('#cars-form-new-used-select').val(),
                 url = baseUrl;
                 if (newUsedToggleValue === 'used') {
                   url += 'for-sale/searchresults.action';
                 } else {
                   url += 'go/search/newBuyIndex.jsp';
                 }
                return url;
             }
           });

Sinon code Snippet:

        QUnit.test('_buildURLForm function', function(){

        QUnit.expect(1);

        var BuildFormURLStub = Sinon.stub(CarSearch.prototype, 'buildFormUrl');// building the sinon stub
        var toggleButton     = $(SampleHtml).find('cars-new-used-toggle');
        $(toggleButton).first().click();                                       //clicking the button

        var baseURL = "http:\\www.cars.com";
        var output = Sinon.once(BuildFormURLStub.withArgs(baseURL));           // passing the argument and and calling the function using sinon once![enter image description here][1]
        var Expected = baseURL + 'for-sale/searchresults.action';
        QUnit.deepEqual(output,Expected,"For new Toggle button clicked");
   });

Am getting the error " The function is undefined"

'undefined' is not a function (evaluating 'Sinon.once(BuildFormURLStub.withArgs(baseURL))')

TypeError: 'undefined' is not a function (evaluating 'Sinon.once(BuildFormURLStub.withArgs(baseURL))')

有帮助吗?

解决方案

You need to pass in an object instead of the prototype:

var carSearchInstance = getInstanceSomehow();
var BuildFormURLStub = Sinon.stub(carSearchInstance , 'buildFormUrl'); 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top