Wednesday
Nov302011

Mock It All Up

We are supporters of Test Driven Development / Behavior Driven Development, and, consequently, we've picked Jasmine as our ultimate testing tool: it is quick, friendly and easy to learn, and our code is tested with every build.

There are many reasons to write/maintain code in a modular manner. When considering testing, the modular code allows each segment/class/flow to be tested separately. Before you object, let me demonstrate one tip that might come handy. Here is a (simplified) class to be tested:

    
function ModalOverlay() {
    var shown = false;

    this.show = function() {
        // roughly will open a dialogue only in half of the total requests
        if (Math.random() < 0.5) {
            shown = true;
        }
    }

    this.hide = function() {
        shown = false;
    }

    this.isShown = function() {
        return shown;
    }
}

That's right! The overlay code is by no means deterministic but still testable as is. How? Let's inspect the well-known Math.random() method:

    
describe("Modal Overlay Test", function() {
    var mocRandomObj;
    var modalOverlay;

    function MocRandomObj() {
        var predefinedRandomResult;

        this.set = function(result) {
            predefinedRandomResult = result;
        }
        
        this.get = function() {
            return predefinedRandomResult;
        }
    }

    beforeEach(function() {
        mocRandomObj = new MocRandomObj();

        // here goes the punch!
        spyOn(Math,'random').andCallFake(mocRandomObj.get);

        modalOverlay = new ModalOverlay();
    });

    describe("when probability is coined", function(){
        beforeEach(function() {
            mocRandomObj.set(0.4);
        });

		it("should show overlay", function() {
			modalOverlay.show();
			expect(modalOverlay.isShown()).toBeTruthy();
		});
	});
});

As demonstrated above, with a big help from spyOn() a fake code block is called and a known "probabilistic" value is returned. You couldn't ask for it to be any more simple! Generalizing the above approach, we can be extremely flexible and mock all kinds of behaviors in almost every granular level, leaving the tested code intact.

We will be more than happy to hear about your testing/mocking tricks and techniques. If you choose to share any tips or constructive criticism of your own, we are here to listen (and respond).

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« First Steps on Amazon's CloudWatch | Main | Javascript Functions as a Mind Map »