What Should Be Tested in JavaScript?

javascripttestingunit testing

At work, we've just started on a heavily Javascript based application (actually using Coffeescript, but still), of which I've been implementing an automated test system using JsTestDriver and fabric.

We've never written something with this much Javascript, so up until now we've never done any Javascript testing. I'm unsure what exactly we should be testing in our unit tests. We've written JQuery plugins for various things, so it's quite obvious that they should be verified for correctness as much as possible with JsTestDriver, but everyone else in my team seems to think that we should be testing the page level Javascript as well.

I don't think we should be testing page level Javascript as unit tests, but instead using a system like Selenium to verify everything works as expected. My main reasoning for this is that at the moment, page level Javascript tests are guaranteed to fail through JsTestDriver, because they're trying to access elements on the DOM that can't possibly exist.

So, what should be unit tested in Javascript?

Best Answer

Test everything you can.

Pure logic can be tested easily.

If your code interacts with the DOM or the network, it's much harder.

If you can abstract out a piece of code to work on an arbitrary DOM element instead of a specific one, then you can test it more easily. (Make the element to work on a parameter).

Code that uses Ajax can be tested by simply calling the callback function with fixed data. I've had some tests where I overwrote $.ajax with my own function. Just make sure you put the real one back when you're done!

What you'll find is that "page level javascript" really means, "tightly coupled code," and if you decouple the parts of the code, you can test them independently.

(Selenium is not a unit testing tool. It's great for high-level scenarios, but you can't test-drive with it, and it doesn't work in an isolated environment.)

Related Topic