2 Comments

ExtJS Unit Testing Using Jasmine

Jasmine LogoIf you want to use Jasmine to unit test your Ext JS 4 application, there are a number of good resources available that can help you get started.

Most of these indicate they are for writing unit tests, but few of them seem to focus on isolating the component or class to be tested. Some even go as far as to show how to load your entire Ext.application for testing. Here I will show what I have done to unit test my Ext JS code using Jasmine.

Just as in all of the examples above, you will need to modify the SpecRunner.html that comes with the standalone distribution of Jasmine. But instead of using a real Ext.application or one made specifically for the test, you just need to set the load path (relative to the location of the SpecRunner.html) and wrap the call that starts Jasmine with an Ext.onReady.

<script type="text/javascript">
  Ext.Loader.setPath('MyApp', '../js/app');
</script>

function execJasmine() {
  Ext.onReady(function() {
    jasmineEnv.execute();
  });
}

In addition, if you want to test custom UI widgets you can add an element to the body of the test runner page where you can later render the widget to:

<body>
  <div id="test"></div>
</body>

With that in place, you just need to require the class you are going to unit test at the top of your spec. For example, here is MyWidgetSpec.js.

Ext.require("MyApp.widget.MyWidget");
 
describe("MyApp.widget.MyWidget", function() {
  var widget;
 
  beforeEach(function() {
    widget = Ext.create("MyApp.widget.MyWidget", {
      renderTo: "test"
      value: "Some Initial Value",
    });
  });
 
  afterEach(function() {
    Ext.destroy(widget);
  });
 
  it("displays the initial value", function() {
    expect($('#test .display').text()).toEqual("Some Initial Value");
  });
});

You might have noted that I am using jQuery in the example. If you are not using jQuery in your application proper, I highly recommend including it in your SpecRunner.html so you have access to it in your tests. Even if it is just to get the text() function I used in the example, it will be worth your while. It definitely beats having to copy/paste helper methods from the Sencha Forums all of the time.

Also consider bringing in the jasmine-jquery extension. It provides a bunch of really useful custom matchers.

Here are gists of the full SpecRunner.html, MyWidgetSpec.js, and MyWidget.js files.