2
votes

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

1
Why to you want to stub the function that you want to test. That makes no sense. Maybe you can explain what you want to test here. - Andreas Köberle
Hi Andreas Koberle i want to check the return value of function only. which will change on the basis of user input. I searched for it more. is it possible to check the value using spy.returned(obj); where object will be the actual returned value and spy will be initialised with the view function itself? - nitansh bareja

1 Answers

1
votes

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

var carSearchInstance = getInstanceSomehow();
var BuildFormURLStub = Sinon.stub(carSearchInstance , 'buildFormUrl');