act:ualise | technology

11 Feb, 2009

Hit the road Jack: OO Javascript testing made easy!

Posted by: j pimmel In: development|javascript|tdd|testing

I’ve long been used to having decent testing frameworks in Java / Groovy / Grails however its taken me a while to stumble upon similar ways to test in Javascript. I tried my hand at using JSMock and then tried MockMe. They both seem very capable but I wanted something quick to test a class created using PrototypeJS‘s Class.create() method. Enter Jack to make it easy!

The example shown uses a mock instance passed to the instance of the containing class, which enables us to verify the functionality of that containing class.

We need to include the jack.js file in our script declarations:

<script type="text/javascript" src="your-path-to/jack.js"></script>

Objects defined using Class.create:

var ContainedObject = Class.create({
	calcMaxMethodName: function() {
		return -1;
	},
	calcMinMethodName: function() {
		return -1;
	},
	getChildren: function() {
		return [];
	}
});

var ContainerObjectIMade = Class.create({
	initialize: function(containedObject) {
		this.delegate = containedObject;
	},
	doSomething: function() {
		return {
			"min": this.delegate.calcMinMethodName(),
			"max": this.delegate.calcMaxMethodName(),
			"children": this.delegate.getChildren()
		};
	}
});

Now for the test:

function testExample() {
	jack(function(){
		var expectedArray = ['foo'];

		var mockObjectUnderTest = jack.create("objectNameKey",
			['calcMaxMethodName', 'calcMinMethodName', 'getChildren']);

		jack.expect("objectNameKey.calcMaxMethodName")
			.exactly("1 time")
			.returnValue(101);
		jack.expect("objectNameKey.calcMinMethodName")
			.exactly("1 time")
			.returnValue(77);
		jack.expect("objectNameKey.getChildren")
			.exactly("1 time")
			.returnValue(expectedArray);

		var containerInstance = new ContainerObjectIMade(mockObjectUnderTest);
		var json = containerInstance.doSomething();

		assertEquals(77, json.min);
		assertEquals(101, json.max);
		assertEquals(expectedArray, json.children);

	});
}

It couldn’t be easier to test your Javascript Objects!

No Responses to "Hit the road Jack: OO Javascript testing made easy!"

Comment Form

About

act:ualise | technical blog

notes, observations and obssessions on software quality, agile software development, testing and grails


part of the EnergizedWork experiment