RND Websites

Debugging Mocha tests in WebStorm

by on May.03, 2012, under Javascript, mocha.js, unit testing

I’m a recent convert to the WebStorm IDE and for Node development especially, the debugger is a godsent. No longer do I need to add console.log statements to my code to figure out what’s going on, I can just set a breakpoint and go from there. Simply awesome! However, I wasn’t able to do this for Mocha test scripts. I tried these instructions that I found, but that didn’t work for me.

When I came across a post on Stack Overflow asking if Mocha could be used as a Node.JS module, I immediately figured out the solution. Create a Node.js script, include Mocha as a module and start the tests like that. Using the Mocha JS API, this was a simple task.

var Mocha = require('mocha'),
	path = require('path'),
	fs = require('fs');

var mocha = new Mocha({
	reporter: 'dot',
	ui: 'bdd',
	timeout: 999999
});

var testDir = './test/';

fs.readdir(testDir, function (err, files) {
	if (err) {
		console.log(err);
		return;
	}
	files.forEach(function (file) {
		if (path.extname(file) === '.js') {
			console.log('adding test file: %s', file);
			mocha.addFile(testDir + file);
		}
	});

	var runner = mocha.run(function () {
		console.log('finished');
	});

	runner.on('pass', function (test) {
		console.log('... %s passed', test.title);
	});

	runner.on('fail', function (test) {
		console.log('... %s failed', test.title);
	});
});

The only problem is the Mocha timeout setting. When you’re debugging, the timer will continue to run, so by the time you are done debugging, the timeout will have fired. Of course, this can be solved by setting the timeout value to a sufficiently high value for debugging. Running the tests can actually be done more easily by invoking mocha from the command line.

Comments Off more...

How to use Mocha.js to unit test YUI

by on Apr.26, 2012, under Javascript, mocha.js, unit testing, 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!

Comments Off more...

Robbed

by on Apr.08, 2012, under Personal

Two nights ago, we were rudely awakened by loud noises coming from downstairs. I immediately knew what was happening: someone was breaking into our house, probably to grab our iMac. By the time I got to the room the bastards were gone, leaving broken glass all over the room. They smashed a window, probably using a sledgehammer. The window was doubleglazed, and the outside pane was almost a centimeter thick. It took them at least five swings to break the glass. But within a few minutes they were through, managed to grab the computer and drive off on their scooter.

We immediately called the police and they responded quickly, sending units to search for the scum that stole our computer. Sadly, but not unexpected, they didn’t find anyone. The police arrived 10-15 minutes later at the house and did their best to calm us down and get our statement. Our neighbours also came out right after it happened. Considering we all just moved here and haven’t really got to know each other, I was very grateful that they were there for us. One neighbour actually saw the direction they took off in, but it didn’t help in the recovery of our computer.

The day after, I just went to work as if nothing happened, but all day I had a knot in my stomach. Luckily, work was a good distraction. That night we had already planned to go out, so we did that, again as if nothing happened. But in the back of my head, the memory still lingered. The exhaustion kicked in when we got home and both of us had a pretty good night’s sleep.

Yesterday, I finally managed to get a good look at the room and the broken glass everywhere. Perhaps foolishly, I let it sink in, because I wanted to trigger the feelings that were slumbering inside. The most prevalent feeling was anger. I’m so mad that someone took a sledgehammer to our house, smashed our window and grabbed our computer that held a lot of personal stuff, like the original photos from the birth of our little girl (luckily we had the best pictures backed up on the net). Last night, I woke up around the same time as the break in happened. I lay awake for an hour, thinking of all the things I would’ve done if I had managed to get down there in time. All the time I felt that knot in my stomach grow bigger. I can still feel it now. I want to get rid of it, I want to get past this and feel safe and happy in my home again. I won’t let those bastards make me feel like a victim, like I somehow deserved what happened. They had no right, whatever they might think about that themselves. I live in a terrific country, where no one has to steal to survive. It’s pure, unadulterated envy that made them do what they did. They saw something they wanted to have, and instead of working for it and earning the money to buy it, they had to invade my home to get mine.

Next week, our window will be fixed, all the broken glass will be removed and hopefully, the room will look like nothing happened, so we can move past this. I hope that whoever did this, will, at some point, be held accountable and be punished for their evil. In the meantime, I will overcome my fear and move on with my life.

Comments Off more...

Fronteers 2011 – The videos

by on Oct.18, 2011, under CSS, HTML, Javascript

All the presentations at Fronteers 2011 have been recorded, and the first presentation (The Future is Native by Aral Balkan) has now been uploaded to vimeo, the other talks will follow soon. View the presentation below:

Aral Balkan | The Future is Native | Fronteers 2011 from Fronteers on Vimeo.

All videos will appear on this page at a later time:
http://vimeo.com/channels/fronteers11#30659519

Comments Off more...

Fronteers 2011 Day 2 – more thoughts

by on Oct.10, 2011, under CSS, HTML, Javascript

The second day promised to match the quality and depth of the talks on the first day and it totally fulfilled that promise. Although it started off a bit rocky for me, because I arrived about 20 minutes late for the first presentation, I still managed to get the most important information out of it. So let’s go through the various talks. (continue reading…)

Comments Off more...

Fronteers conference 2011 Day 1 – my thoughts

by on Oct.07, 2011, under CSS, HTML, Javascript

The past two days, I’ve been at the Fronteers 2011 conference. Fronteers is the Dutch trade union for front end developers and this is the fifth year they’ve organized this conference. Last year was the first time I went to the conference, which was okay. This year’s conference, however, was very much worth the time and money spent.

(continue reading…)

Comments Off more...

30 days

by on Sep.25, 2011, under CSS, HTML, Javascript, Personal

A few days ago, I watched the TED presentation by Matt Cutts where he explains how he changed things in his life by trying out new things for thirty days. Towards the end of his presentation he also admits that it doesn’t always work, like when he tried to go thirty days without sugar. However, I think that the essence of his story might work for me. I usually set enormous goals for myself and then never start them, because I decide upfront that there’s no way I can achieve said goals.

One of those things is improving my JavaScript and general programming skills. I try to keep up with new developments, but I hardly ever sit down and play around with code, unless my day job requires it. Of course, my life has changed enormously after the birth of my daughter and it’s been a very tiring few months. But that is quieting down now, so I feel this is a good time to start this experiment.

So what am I going to do? For the next thirty days (starting tomorrow, Monday 26th), I’m going to spend at least two nights a week on improving my skills, instead of improving being a couch potato. Because my kid usually doesn’t sleep before 8pm, and I need to get some sleep as well, a night will consist of two to three hours. So, let’s see how it went on October, 26th!

Comments Off more...

Recreating a C64 game

by on Mar.24, 2011, under Javascript

To challenge myself as JavaScript programmer and to learn new things, I’ve decided to try and rebuild a Commodore 64 educational game called “Topography Netherlands”. I couldn’t find a C64 video of it, but this MSX version is basically the same. The idea is that the game gives you a name of a Dutch city and you need to fly there as fast as possible. The goal is to score as many points as you can in a set amount of time. The game was intended to teach younger children the location of Dutch cities. Later versions of the game also offered German and European maps.

As you can tell from the video, the game isn’t that complex. Here’s my shopping list:

  • an animation of a helicopter
  • a map of the Netherlands
  • coordinates of all Dutch cities
  • a clock
  • a scoring system
  • a randomizer to select different cities
  • some form of collision detection to determine if the helicopter is at the required location on the map
  • a way to convert keyboard presses into directional controls

To make things slightly more interesting, I want to use a canvas element. It would probably be easier to use a collection of divs, but where’s the challenge in that, right?

I’ve already found a nice, large map with all Dutch municipalities on it that I can use as a basis for my map and for my coordinates list.

As I’m doing this in my spare time, I’m giving myself one month to finish it. Also, I’m not going to use any library (except for excanvas.js to make it work in IE as well). Reason for this is that I’m not used to work without the safety net of a framework, and I notice that it limits me in being a good JS programmer (basically, I’m too used to the Prototype.js idiom). This will probably mean that I’ll need to look at code optimization at some point.

I’ll start on this next week, after a weekend of relaxing. I hope you (read: someone) will follow my endeavours and maybe learn something from it (as I hope I will).

Comments Off more...

The problem of massive CSS

by on Dec.06, 2010, under CSS

In the past few years, I’ve worked on several big websites as part of a front end team. And all those sites have the same problem: a cancerous growth of CSS. The problem starts out small; a designer changes the look of a new component of the site in such a way that existing CSS classes can’t be used, so the developer adds some new classes. However, over the years this process turns a few hundred lines of CSS into a few thousand lines (or even more than a few). And at some point the developer might not even try to reuse CSS code, because it’s easier to add a few more classes than to find the proper classes in all those lines of CSS. And so the problem of massive CSS is born.

So what is the solution for this problem? In my opinion, the solution has multiple layers. Firstly, for a large site a very strictly adhered style guide and component guide is a requirement. It might not be as much fun for the designers, but it is a very good way to maintain cohesion in the designs across a site. Secondly, build the component with reusability in mind. Don’t make them location dependent (i.e. it should be possible to put a component in the main column and in the sidebar without adding new CSS). This is quite difficult, but not impossible. If there is no other way, make sure to document this in your CSS and HTML. However, the hardest part to solving the issue is getting people on board with any new solution. People don’t like change, and there are actually people that thrive in the chaos of massive CSS.

Technically speaking, I think the best solution is Nicole Sullivan‘s Object Oriented CSS approach. Although the link goes to Github, it’s not only a technical solution, it’s a mindset solution (just like OOP). You need to learn to “see” the “objects” in a page that can work with the OOCSS approach. OOCSS also isn’t a silver bullet, you can’t use it for every single part of your website. However, it can work for the interface elements of your site: the elements that keep popping up all over your site. Things like content boxes, a picture with some text or a form field and label. The clue of OOCSS is figuring out a singular way of building a component and then sticking with it. Of course you can extend a component so that it becomes a new component (just as you extend a class in OOP), but you shouldn’t have two components that look similar on the same level in your “OOCSS hierarchy”.

Comments Off more...

HTML5 forms with fallback for non-supporting browsers

by on Oct.18, 2010, under Javascript

Last week, I did some research into creating fallbacks for the new HTML5 form elements, such as email fields, date fields, etc. As it turns out, this is very easy. I used Modernizr for the feature detection. Although it’s just a 5k script, you could easily extract the required code from it if you want to keep your footprint to a minimum.

Based on the Modernizr results, I applied a CSS class for design purposes and attached event handlers. For example, the code below handles the “required” attribute.

function validateRequired(e) {
var fld = e.element(),
ph = fld.getAttribute('placeholder') || '';
if (fld.value === '' || fld.value === ph) {
console.log('field ' + fld.id + ' is required');
fld.removeClassName('validated');
} else {
fld.addClassName('validated');
}
}

if (!Modernizr.input.required) {
$$('input[required]').invoke('addClassName', 'required')
.invoke('observe', 'blur', validateRequired);
}

I use Prototype.js as my framework of choice, but it can be done just as well with other frameworks or plain javascript. As long as you use Element.getAttribute you can access the new attributes without any problems in all browsers. Of course, this is just proof-of-concept code, so it needs some tidying up for actual production use. I’ll probably create a full Prototype.js library of modules to handle the various attributes and field types. I’m also figuring out a good way to handle data-* attributes so you get an easy way to access those. My aim is to stay as close as possible to the official spec for those interfaces.

I’ve tested the code in IE6, IE7, IE8, Firefox 3.0, Firefox 3.6, Safari 5 (Win), Chrome 6 and Opera 10 and they all work as expected.

Comments Off more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Categories