Chapter 9. Testing and Debugging

All developers test, to some degree or another, when they’re programming. Even just running the code manually is a form of testing. However, what we’re going to cover here is automated testing in JavaScript—i.e., writing specific assertions that run automatically. Automated testing won’t eliminate bugs from your code, but it is a measure to effectively reduce the number of defects and to prevent older bugs from creeping back into the codebase. There are lots of great resources out there justifying and explaining different types of testing. So, rather than creating an inferior rehash of those, this chapter will focus on the specifics of testing in JavaScript as opposed to other languages.

Testing in JavaScript isn’t really ingrained into the culture, so many JavaScript developers don’t write any tests for their code. I think the main reason is that automated JavaScript testing is difficult—it doesn’t scale. Let’s take jQuery for example. The library has hundreds of unit tests and about 10 different test suites to simulate the various environments it’s expected to run in. Each test has to be run once in every suite. Now, take a look at the browsers jQuery supports:

  • Safari: 3.2, 4, 5, nightly

  • Chrome: 8, 9, 10, 11

  • Internet Explorer: 6, 7, 8, 9

  • Firefox: 2, 3, 3.5, 3.6, nightly

  • Opera: 9.6, 10, 11

So, that’s 5 browsers with about 20 versions among them, and each suite needs to be run on every browser version. You can see how the amount of tests that have to be ...

Get JavaScript Web Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.