Testing Ext Objects Using JsUnit

We are using JsUnit to test our JavaScript code.  Most of the time we end up needing to stub out methods, save the method pointers and then put the original method back once done with the test.  This is very easy to do in JavaScript so why not!

An example test method usually looks like this:

1
2
3
4
5
6
7
8
9
10
11
function test_orderTabs() {
  var originalFunction = PTC.infoPage.TabSet.fooMethod;
  PTC.infoPage.TabSet.fooMethod = function() {
    //Do somthing else instead
  };
 
  //Do testing
 
  //Put back original function
  PTC.infoPage.TabSet.fooMethod = originalFunction;
}

Recently while doing some test driven development, I thought of extending our Ext component to make a Mock object.  This is really the same idea that we use in Java for JUnit testing.  The nice thing that happens when we do this in JavaScript is that we don’t need to worry about cleaning up function pointers!

1
2
3
4
5
6
7
8
9
PTC.infoPage.TabSetMock = Ext.extend(PTC.infoPage.TabSet, {
  fooMethod: function(){
  //Do Stuff
}
});
 
tabSetMock = new PTC.infoPage.TabSetMock({
  fooConfig: BarItems
});

Then later in the test method all I needed to do was something like the following:

1
2
3
function test_orderTabs() {
  var result = tabSetMock.fooMethod();
}

The benefit is that you don’t have to save function pointers. The mock was created in the context of the test method so once the test is over the memory of the mock is eased.