A Reusable Builder Class for Javascript Testing

Posted by Liam McLennan on Geeks with Blogs See other posts from Geeks with Blogs or by Liam McLennan
Published on Tue, 23 Mar 2010 16:01:12 GMT Indexed on 2010/03/23 22:13 UTC
Read the original article Hit count: 545

Filed under:

Continuing on my series of builders for C# and Ruby here is the solution in Javascript. This is probably the implementation with which I am least happy. There are several parts that did not seem to fit the language.

This time around I didn’t bother with a testing framework, I just append some values to the page with jQuery. Here is the test code:

var initialiseBuilder = function() {
	var builder = builderConstructor();
	
	builder.configure({
		'Person': function() { return {name: 'Liam', age: 26}},
		'Property': function() { return {street: '127 Creek St', manager: builder.a('Person') }}
	});
	return builder;
};

var print = function(s) {
	$('body').append(s + '<br/>');
};

var build = initialiseBuilder();

// get an object
liam = build.a('Person');
print(liam.name + ' is ' + liam.age);

// get a modified object
liam = build.a('Person', function(person) { person.age = 999; });
print(liam.name + ' is ' + liam.age);

home = build.a('Property');
print(home.street + ' manager: ' + home.manager.name); 

and the implementation:

var builderConstructor = function() {
	var that = {};
	var defaults = {};
	that.configure = function(d) {
		defaults = d;
	};	
	that.a = function(type, modifier) {
		var o = defaults[type]();
		if (modifier) {
			modifier(o);
		}
		return o;
	};	
	return that;
};

I still like javascript’s syntax for anonymous methods, defaults[type]() is much clearer than the Ruby equivalent @defaults[klass].call(). You can see the striking similarity between Ruby hashes and javascript objects. I also prefer modifier(o) to the equivalent Ruby, yield o.

© Geeks with Blogs or respective owner