Friday, 29 August 2008

jsUnit testing a method of a class with a boring constructor

Today I wanted to introduce some jsUnit testing in an old class. In particular I wanted to test a single method in isolation but I could not instantiate the object itself since the constructor had dependency on other files.

[source:js]

load("ClassToTest.js");

function testMyMethod() {

var object = new ClassToTest(); // This does not work since

//ClassToTest has a boring constructor!

object.runMethod();

//do some asserts

}

[/source]

The trick is to replace the object with a new one which has the same prototype but an empty constructor:

[source:js]

load("ClassToTest.js");

function NewClass() {}; // empty constructor or whatever you like

NewClass.prototype = ClassToTest.prototype;

function testMyMethod() {

var object = new NewClass(); // This works, since

// it has an empty constructor

object.runMethod(); // this exists and it is the same

//method living on ClassToTest

//do some asserts

}

[/source]

1 comment: