Testable Frontend JavaScript Anti-patterns

Software testing starts when you write the code that will be tested. In these two articles, Shane Tomlinson discusses some anti-patterns that will make your JavaScript frontend code difficult to test. He explains how to detect these anti-patterns in your code and then shows how to refactor your JavaScript to be easier to read, to reuse and to test.

The first article presents a basic JavaScript sample application that contains several common anti-patterns and their solutions. Some of these anti-patterns are inline Javascript, Javascript code that is embedded in an HTML file. This code is impossible to include in an external unit test harness. Another anti-pattern are poorly constructed DOM event handlers where the event handler logic is mixed with form submission logic. This results in an inflexible mixture of concerns. This article addresses each of the problems outlined in the sample code so that the front end code becomes easier to test.

The second article refactors the sample JavaScript code so that it becomes easier to read, to reuse and to test. After the refactoring, testing begins: a test harness is created, an XHR mock is developed and finally, a full unit test suite is added. Each of the anti-pattern discussed in the first article is refactored with detailed explanations. The conclusion of the article is that “Writing testable code is often a challenge, but the basics are easy once you are used to it. Before writing a single line of code, start with the question “how am I going to test this?” This simple question will end up saving countless hours and give you confidence when refactoring or adding new features.”

Read these two articles on https://shanetomlinson.com/2013/testing-javascript-frontend-part-1-anti-patterns-and-fixes/ and https://shanetomlinson.com/2013/writing-testable-javascript-part-2-refactor-away-anti-patterns/