Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
Jasmine Testing: Param(s) passed to a method.

Recently, I’ve been using a nice way to test if the correct arguments have been passed to a method. This uses a neat property of jasmine where you set up the method you want to test as a mock and have an expectation inside the mock.

The only caveat is you have to set an expectation that your mock get’s called, otherwise if it never gets executed the test will also never fail.

Step by Step

1) Set up the spy on the method for which you want to test the params.
2) Set up the expectation to compare a param to an expected value.

spyOn(App.Views.MasterView.prototype, 'initialize').andCallFake(function() {
 expect(arguments[0].template).toEqual(JST['my_templates/simple_view']);
});

3) Call something that should call the method under test with the correct params.

var router = new App.Routers.ViewRouter;
router.simpleViewInit();

4) Set up an expecatation that makes sure the method under test get’s actually called.

expect(App.Views.MasterView.prototype.initialize).toHaveBeenCalled();

Here you go, now it is easy to test if a method is called with the expected param(s).

The complete test.

describe('App.Routers.ViewRouter', function() {
  beforeEach(function() {
    Backbone.history.start();
  });

  afterEach(function() {
    Backbone.history.stop();
  });

    describe('#simpleViewInit', function() {
        it('call initialize on the MasterView with the simple_view template', function() {
        spyOn(App.Views.MasterView.prototype, 'initialize').andCallFake(function() {
             expect(arguments[0].template).toEqual(JST['my_templates/simple_view']);
          });
          var router = new App.Routers.ViewRouter;
          router.simpleViewInit();

         expect(App.Views.MasterView.prototype.initialize).toHaveBeenCalled();
        });
    });
});

The code that is under test.

App.Routers.ViewRouter = App.Routers.BaseRouter.extend(
{
    routes: {
        'example1': 'example1'
    },

    initialize: function() {
        ...
    },

    simpleViewInit: function() {
        this.simpleViewRecord = new App.Models.SimpleViewRecord();
        this.simpleView = new App.Views.MasterView({
            el: '#view_element',
            model: this.simpleView,
            template: JST[''my_templates/simple_view''],
            state: 'expired'
        });

        this.simpleViewInit.fetch({
            success: function(model) {
              model.trigger('change');
            }, silent: true
        });
    }
});

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *