Chapter 3. Testing Frontend Code

Testing JavaScript browser code has been notoriously considered hard, and although there are many complications while dealing with cross-browser testing, the most common problem is not with the testing process, but rather that the application code itself is not testable.

Since every element in the browser's document is accessible globally, it is easy to write a monolithic piece of JavaScript code that deals with the whole page. This leads to a number of problems, and the biggest one is that it is pretty hard to test.

In this chapter, you are going to get the best practices on how to write maintainable and testable browser code.

To implement the user interface, you are going to use jQuery, a well-known JavaScript library that abstracts the browser's DOM in a clean and simple API that works across different browsers.

To make the writing of the specs easier, we're going to use Jasmine jQuery, a Jasmine extension that adds new matchers to perform assertions on jQuery objects. To install it and its jQuery dependency, download the following files:

Place them inside the lib/ folder, and add them to SpecRunner.html:

<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript" src="lib/jasmine-jquery.js"></script>

As seen so far, we have already created separate abstractions to handle both an investment and its associated stock. Now it is time to develop this application's user interface, and to achieve a good result, which is all a matter of organization and good practices.

The same principles of software engineering that you apply on your server-based code must not be left behind when writing your frontend JavaScript code. It is still important to think about components and proper separation of concerns.

Thinking in terms of components (Views)

We've talked about the monolithic JavaScript codebases that plague most of the Web, codebases that are impossible to test. And the best way not to fall into this trap, is by coding your application driven by tests.

Consider the mockup interface of our Investment Tracker application:

Thinking in terms of components (Views)

Investment Tracker mockup interface

How would you go on implementing it? It is easy to see that this application has two different responsibilities:

  • One to add an investment
  • And another to list the added investments

So we could start by breaking this interface into two different components. And to better describe them, we are going to borrow a concept from MVC frameworks , such as Backbone.js, and call them Views .

So here it is, at the top level of the interface, with two base components:

  • NewInvestmentView: This will be responsible for creating new investments
  • InvestmentListView: This is going to be a list of all added investments
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.134.17