Tech Rocks


An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more...

Thursday, June 8, 2017

Writing Testable Code in JavaScript

Whether we’re using Node paired with a test framework like Mocha or Jasmine, or spinning up DOM-dependent tests in a headless browser like PhantomJS, our options for unit testing JavaScript are better now than ever.

However, this doesn’t mean the code we’re testing is as easy on us as our tools are! Organizing and writing code that is easily testable takes some effort and planning, but there are a few patterns, inspired by functional programming concepts, that we can use to avoid getting into a tough spot when it comes time to test our code. In this article, we will go through some useful tips and patterns for writing testable code in JavaScript.

Keep Business Logic and Display Logic Separate
One of the primary jobs of a JavaScript-based browser application is listening to DOM events triggered by the end user, and then responding to them by running some business logic and displaying the results on the page. It’s tempting to write an anonymous function that does the bulk of the work right where you’re setting up your DOM event listeners. The problem this creates is that you now have to simulate DOM events to test your anonymous function. This can create overhead both in lines of code and the time it takes for tests to run.


Post a Comment