Tuesday, April 12, 2011

Using QUnit with RequireJS

I have really been enjoying James Burke’s RequireJS library: http://blog.dohertycomputing.com/post/3466960658/requirejs and have recently applied it to a project at my day job. When it came to testing the application, I decided on QUnit for unit testing, and started poking into using it with RequireJS. 


I was able to successfully run tests using the RequireJS approach, i.e., define a test module, with the code to be tested as explicit dependencies, and waiting to start the tests until the module and all its dependencies are loaded. Async behavior is handled via QUnit.stop()/start() as described in the QUnit API: http://docs.jquery.com/QUnit

define(
        [
            “my/moduletotest1”,
            “my/moduletotest2”,
            “my/moduletotest3”,
        ],
        function (moduletotest1, moduletotest2, moduletotest3) {
            return {
                RunTests: function () {
                    test(“mod1test”, function () {
                        QUnit.stop();
                        moduletotest1.ajaxyMethod(arg, function(result) {
                              deepEqual(result, matchExpression);
                              QUnit.start();
                        });
                    });

                    test(“mod2test”, function () {
                        QUnit.stop();
                        moduletotest2.ajaxyMethod(arg, function(result) {
                              equal(result, matchExpression);
                              QUnit.start();
                        });
                    });
                    …
                }
            };
});

Then in the QUnit page script:

QUnit.config.autostart = false;
require(
          [
            “UnitTests/TestModule”,
          ],
          function (testModule) {
            QUnit.start();
            testModule.RunTests();
          }
);

Works like a charm!


No comments:

Post a Comment