Search This Blog


Monday, June 22, 2009

Mocking and Stubbing in Javascript

I have just stumbled across a JQuery unit testing and mocking framework that I would like to share: jqunit and jqmock.

Amid a plethora of Javascript unit testing and mocking frameworks ( such as qunit, qmock etc), there seems to be only one mocking framework that's serious enough to implement the stubbing behavior, and that's jqmock. Incidently, a lack of mock framework support underscores how undeserved the Javascript community is.

Here's a quick demonstration on how to stub the annoying "alert" method call and verify that the message shown on the alert dialog box is correct. Let's say that we have the following requirement: When a link is clicked, a message box should pop up and say "Hello world new!". Here's the Javascript ( mainscript.js), using JQuery:

function hello2() {
    alert("hello world new!");



And here's how we can test the code, using AAA syntax:
with (jqUnit) {
test("hello world test Me", function() {

    var alertMock = new jqMock.Mock(window, "alert");
    alertMock.modify().args("hello world new!").returnValue();
     //clean up


In the arrange part, we just tell the code to look out for window.alert, and if the argument to that method is "hello world new!", then we mock the call.

In the act part, we call the method under test, in this case, it's hello2().

In the assert part, we check that the window.alert method is indeed called, and the argument is indeed as expected by calling the verify() method.

jqUnit and jqMock is nice. But as far as I know it can't test AJAX call, yet. I am looking forward to the inclusion of that feature. 

1 comment:

Kenneth Ko said...

Thanks for looking at the library. It's unfortunate that I've received almost no feedback for jqmock, so there's little incentive to maintain the project.
So much of the functionality in JS is now for UI eye candy, which doesn't need mock testing. I guess mocking in JS is just one of those things which won't really take off until the JS starts getting complicated enough to warrant that type of testing.