Skip to content

Instantly share code, notes, and snippets.

@NickJosevski
Created January 5, 2012 10:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save NickJosevski/1564578 to your computer and use it in GitHub Desktop.
Some QUnit basics as part of a blog post
/// more info: http://blog.nick.josevski.com/2012/01/05/unit-testing-javascript-methods-that-contain-jquery-ajax-calls
test("check if methodUnderTest completes successfully (mockJax way)", function () {
// Arrange
var jsonText = '{"id": "123","fieldName": "mj-fbs", "data": "fbs-text"}',
fieldBeingSaved = $('<input name="mj-fbs" Text="fbs-text"></input>'),
busyImg = $('<img id="mj-fbs-loading" alt="should-get-replaced-by-success-method"></img>');
$.mockjax({
url: '/Action/Method',
dataType: 'json',
contentType: 'application/json',
response: function () {
this.responseText = jsonText;
//Assert
same($('#mj-fbs-loading').attr('alt'), $d.check(), "was expecting the alt attribute to change");
// Cleanup
$("#mj-fbs-loading").remove();
}
});
$('body').append(busyImg);
// Act
$d.methodUnderTest(fieldBeingSaved);
// Assert is chained onto the response method above, otherwise it executes early
});
/// http://stackoverflow.com/questions/522437/qunit-parameterized-tests-and-mocking
test("check if methodUnderTest completes successfully (clean jQuery way)", function () {
// Arrange
var options,
jsonText = '{"id": "123","fieldName": "reg-fbs", "data": "fbs-text"}',
expectedData = $.parseJSON(jsonText),
fieldBeingSaved = $('<input name="reg-fbs" Text="fbs-text"></input>'),
busyImg = $('<img id="reg-fbs-loading" alt="should-get-replaced-by-success-method"></img>');
jQuery.ajax = function (param) {
options = param;
};
$('body').append(busyImg);
// Act
$d.methodUnderTest(fieldBeingSaved);
options.success(expectedData, null, null);
// Assert
same($('#reg-fbs-loading').attr('alt'), $d.greenCheckGif(), "was expecting the alt attribute to change");
// Cleanup
$("#reg-fbs-loading").remove();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment