Question

I'm starting to delve into some work with JavaScript and i'm trying to get a feel for how I should be writing testable JS code. My background is primarily Java which i'm quite comfortable with but I have no JavaScript experience. after some reading, I was going to use js-test-driver as my unit test framework, but I am open to suggestions here as well. With Java, my approach has always been breaking things down into small methods which accept something and return something... With JavaScript, I figured I would take a similar approach by separating any DOM manipulation and the actual logic into 2 separate functions. For example:

function sumValues(valA, valB) {
return (valA + valB);
}

function displayResult(result) {
document.getElementById('result').innerHTML = 'result';
}

So, any business logic would be easily testable.

Am I on the right track here or is there a better way to do things? Any recommended reading on this topic that is JS specific? Thanks for any ideas

Was it helpful?

Solution

Breaking code into logical units still applies in JavaScript of course. As to how exactly you'd structure your code and organize reusability, there are many different ways to choose from - too many to list here and also a matter of personal preference. From prototypal inheritance, to pseudo-classical inheritance; using frameworks like backbone.js, angular.js, require.js, yui, google closure...

Regarding your example you'd probably start separating your code into views and controllers which are testable separately, and have only the view manipulate the DOM. I'd check out backbone.js for more.

A book that really helped me get started with test driven development in JavaScript (and also learn about JavaScript at the same time) is Test-Driven JavaScript Development by Christian Johansen.

I'm using JsTestDriver, it's a great software and definitely good to use. But before using it large scale I'd evaluate other products too, because development in JsTestDriver has been going really slow recently.. Buster.JS looks promising. Another interesting runner is Testem which allows you to use different test frameworks, like Mocha and Jasmine.

I can also recommend Sinon.JS as mocking toolkit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top