Mock Ajax in QUnit w/ iFrame Environment

In our QUnit w/ iFrame environment, we have two jQuery objects – one for the parent ($$) and one for the iFrame ($).  To mock ajax, I decided to go with the mockjax library because it worked out of the box with my set up as opposed to Sinon JS and jQuery Fixture.

In my test setup where I load the iFrame, I have a line that sets the iFrame’s jQuery object to $ and QUnit’s iFrame object as $$.  Use $.getScript to import the mockjax library to the iFrame’s jQuery object.

$.getScript(referencePath + “../jquery.mockjax.js”);

Once this is done, $.mockjax should be available for your tests.  Use the same examples in the mockjax github.

// set up mock jax to http://url
var id = $.mockjax({
url: ‘http://url’,
dataType: ‘json’,
responseTime: 100,
responseText: {
text: ‘Hello World!’
}
});

// forced ajax call, remove mocked ajax on ajax completion
$.ajax({
url : ‘http://url’,
error : function(jqXhr, status, statusText) {
ok(false, ‘error’);
},
success: function(data) {
equal(data.text, ‘Hello World!’, “Check mock data”);
},
complete: function() {
$.mockjaxClear(id);
}
});

The API was simple enough to work on the first try.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s