David Jones

Testing jquery interactions with jasmine

The first thing we will need to have a copy of is the jasmine-jquery extension that gives us the jQuery matchers needed to test interactions with the DOM. The documentation and download can be found here.

Odds are we are not going to have any HTML at this point so we will need to create a fixture to run our tests against. To create a fixture we will need to utilise another library. This one is called jasmine-fixture. The documentation and download can be found here.

Now we need to include then into our test file. I am using requireJS for this so the top of my test file will look something like this.

define( [ '../modules/Interactions', '../utils/jquery', '../utils/jasmine-fixture', '../utils/jasmine-jquery' ], function( Interactions ) {

This line of code includes the module we want to test, in this case we want to test our Interactions module, jQuery, jasmine-fixture and jasmine-jquery. We now have everything we need to write some tests.

Now we can set up a fixture. Lets look at how we can do this.

We now have access to the "affix" method. Lets look at how we can construct the following HTML using the "affix" method.

<div>
    <a href="#" class="js-toggle" data-area="to-toggle">Click here</a>
    <div class="js-to-toggle" style="display: none;">Hidden area</div>
</div>
var container = affix( "div" );

container.affix( "a[href="#"][class="js-toggle"][data-area="to-toggle"]" );
container.affix( "div[class="js-to-toggle"][style="display: none;"]" );

With this in place we are now able to spy on the click even of the a tag and check the visibility of the hidden div. Lets look at the code.

var spy = spyOnEvent( '.js-toggle', 'click' );
$( '.js-toggle' ).click();
expect( 'click' ).toHaveBeenTriggeredOn( '.js-toggle' );

interactions.toggle( { target: $( '.js-toggle' ), preventDefault: function() {} } );
expect( $( '.js-to-toggle' ) ).toBeVisible();

The first part of this sets up a spy on the click event of our .js-toggle element. We then simulate a click on said element and use the toHaveBeenTriggeredOn method of jasmine-jquery to test if the cick was even made.

The second part triggers our toggle method from our Interactions object. This is a method from the object we originally wanted to test. We need to pass in the event parameter so we know what our target element is and so we do not get an error when we try and use the preventDefault method.

This is a very basic introduction but more information can be retrieved from this repo that I set up of my testing suit. I use Grunt to run my tests and Jasmine as my main testing library.

If you have any questions feel free to get in contact.

Resources

jasmine-fixture

jasmine-jquery