How to use Mocha.js to unit test YUI

We’ve recently started using YUI as the basis for a new version of our product. It’s a very solid library, which provides a lot of high quality code. And although YUI has a nice testing framework as well, we wanted to use Mocha.js, so we could run tests continuously. At first, it was unclear how to integrate YUI into Mocha tests, but in the end the solution was very simple:

var path = require("path"),
    YUI = require("yui3").YUI,
    chai = require("chai"),
    expect = chai.expect;

(function () {
    describe("MyModule", function () {
        var Y, myModule;

        before(function (done) {
            Y = YUI({
                modules: {
                    'mymodule': {
                        fullpath: path.join(__dirname, '../modules/mymodule.js')
                    }
                }
            }).use(['base','mymodule'], function () {
                done();
            });
        });

        beforeEach(function (done) {
            myModule = new Y.MyModule();
            done();
        });

        it('should instantiate the MyModule class', function (done) {
            expect(myModule).to.be.a('object');
            done();
        });

        it('should have a title', function (done) {
            myModule.set('title', 'test');
            expect(myModule.get('title')).to.be.equal('test');
            done();
        });

        it('should have a description', function (done) {
            myModule.set('description', 'test description');
            expect(myModule.get('description')).to.be.equal('test description');
            done();
        });
    });
})();

The trick is to use the ‘before’ method of Mocha.js to create a YUI sandbox and assign that to a variable that is in the larger scope, so it can be accessed in the other classes. To make sure everything has loaded, the ‘before’ method’s ‘done()’ call should be done inside the callback function of YUI’s use method.
And finally, the required YUI modules for custom modules aren’t loaded properly, unless they are mentioned in the use method’s first parameter.

Questions? Ping me on Twitter!