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

July 19, 2012 Georg Apitz

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

About the Author

Biography

Previous
Testing within an ActiveRecord block
Testing within an ActiveRecord block

Following on from the article about ActiveRecord blocks and a similar topics at the office book club, I've ...

Next
Universities Mine for Better Grades
Universities Mine for Better Grades

Unless you attended in the past couple of years, college looks a lot different than it used to. Admissions ...