Getting Started with Unit Testing Javascript

Learn about unit testing JavaScript issues and DOM unit testing JavaScript issues.

Unit testing JavaScript issues

Unit testing for JavaScript is a big, somewhat contentious subject. For years, JavaScript’s testing tools were significantly less powerful than Ruby’s. Although the Ruby tools are more flexible, the JavaScript tools are more than powerful enough to be useful.

And yet, many projects don’t unit-test JavaScript code much, because there are significant impediments to writing good JavaScript tests:

  • The ecosystem is still complicated. There are many different tools and, it’s hard to differentiate between them.

  • The major frameworks don’t have the same level of testing support that Rails does. To some extent, this is getting better.

  • Many JavaScript code is written to be strongly entangled with the DOM. This makes it harder to test the logic.

The last point is probably the most important, so let’s elaborate.

In the discussion of Rails models and controllers, we talked about separating business logic from the database and from the Rails framework to make it easier to test the logic in isolation. We’ve also claimed that isolating the business logic is good not just for testing but also for making the long-term cost of change lower in the codebase.

DOM unit testing JavaScript

Most JavaScript code is ultimately about responding to user action and changing elements in the DOM. And a lot of idiomatic JavaScript code completely intertwines business logic with the DOM to make the code hard to understand and change. Although we won’t cover the popular JavaScript frameworks here, they tend to do a good job of isolating business logic to allow testing, even if not all of them are as tightly integrated with the testing framework Rails.

DOM example

For example, the JavaScript code we wrote in Testing JavaScript: Integration Testing uses the DOM as the source of truth for the order of the tasks. The code queries the DOM to find the previous and next tasks when the time comes to reorder them. While that might be fine for something as simple as reordering tasks, it’s already a little tricky to read if we don’t know the expected DOM structure. Adding simple extensions, like hiding the up or down buttons for the first and last tasks, isn’t clear. In this chapter, we’ll take another swing at that code, attempting to drive it from unit testing rather than integration testing.

Get hands-on with 1200+ tech skills courses.