Backbone and Require how to add Qunit

前端 未结 1 409
一生所求
一生所求 2021-01-01 03:13

I\'m using Backbone and Require.js. Everything works great but, I would like to add some unit tests to my application. I decided use Qunit.js.

In my main.js<

1条回答
  •  -上瘾入骨i
    2021-01-01 03:28

    Fantastic question, and one that I see all the time.

    I actually solved this by creating what I dubbed a "bootstrap" paradigm, but call it whatever you want. The key is that the Backbone view does not render itself, but instead whomever consumes it is responsible for that. You'll run into issues with fetch() and the like, so thankfully this solves that too.

    The goal: Don't unit test render and just skip it all together!

    Your view becomes something like this:

    require(function () {
        var view = Backbone.View.extend({
            // initialize is executed on new, just as you found
            initialize: function (options) {
                _.bindAll(this);
    
                // Create models, initialize properties, and bind to events here.
                // Basically only do __UNEXPENSIVE__, non-dom-changing things that
                // you don't care get executed a lot.                
    
                this.someCollection = new Backbone.Collection();
                this.someCollection.on('add', this.onSomeCollectionAdd);
            },
    
            // bootstrap is for server-side operations that you don't want executed
            // by every single test.
            bootstrap: function () {
                this.someCollection.fetch().done(this.render);
            },
    
            render: function () {
                this.$el.html(...);
            },
    
            first_test_func: function () {
    
            }
        });
    
        return view;
    });
    

    How this would be consumed in your app:

    require(['viewpath'], function (myView) {
        var instance = new myView({ el: $('#something') });
        instance.bootstrap(); //triggers fetch, or if no fetch needed, just render
    });
    

    This can now be unit tested without worry.

    define(['jquery','qunit','view/eventsView'], function($,qunit,EventsView){
    
        test( "first_test_func", function() {
            // Now this line won't call the server, or render.
            // You can isolate/test what you want.
            var eventsView = new EventsView();
            var result = eventsView.first_test_func(2,2);
            equal( result, 4, "2 square equals 4" );
        });
    });
    

    Use SinonJS

    I strongly recommend checking out SinonJS. It's amazing for unit testing JavaScript, particularly Backbone implementations due to its powerful mocking which can be used from preventing the rendering and server calls (fetch, save, etc) from actually hitting the server while still allowing you to assert they got called.

    0 讨论(0)
提交回复
热议问题