JavaScript: Cleaning Up Your Code

Will Pocklington
Mar 20 · 9 min read

Even though you are a programming master, eventually you will need to check your code for bugs and make sure it performs as expected under every circumstance. That is where testing frameworks and debugging tools enter the picture. Today we will investigate the tools available to clean up and test and your JavaScript code.

Debugging

Debugging is one of the most important task for any developer to go through. It is the act of finding problems or “bugs” with your code and resolving those problems before the final product is completed. Although it could be considered as the final step of development, after you have finished coding, it is good practice to debug your code throughout your development process.

Before we begin, it is important to understand the nature of the programmer’s worst enemy: what is a bug? A bug is a term used to describe a problem in a program which prevents it from achieving the desired results of the programmer. For example, running a calculator program that does not have any protections on what can be entered in division could output erroneous answers when a user attempts to divide by zero. The term bug was first used by Grace Hopper after the operators of a Mark II computer discovered a moth in a relay which caused the computer to output erroneous results. If a bug represents a problem, obviously we want to get rid of it. The main problem with bugs is that they are sometimes difficult to find during the production phase, which is where debugging comes into play.

Many JavaScript programmers use console.log() to debug their code. Although it can get the job done, using console.log() can become inefficient in a large code base. Fortunately, there are debuggers available which can make your life easier. A debugger is a program with features focused on helping you pinpoint the problem in your code. If you are reading this post through a modern internet web browser such as Chrome, Firefox, Safari, Edge or Opera on your computer, chances are that they already have a built-in JavaScript debugging tool. Basic debugging tools such as breakpoints and line by line code execution are common between these browsers. In this post, we will showcase the debugging suites found in Chrome and Firefox.

Quick “Hello World” demo using Firefox and Chrome built in debugger.

Chrome: Among the best dev tools for JS, Chrome includes the standard console, network and performance monitoring, and security features.

To open the debugger, press F12 or right-click on the page and click “inspect”.

Firefox: Previous versions needed an extension called Firebug to have access to dev tools, but recent versions have included the extension by default. Firefox’s dev suite is comparable to Chrome’s dev tools.

Similar to Chrome, press F12 or right-click on the page and click “inspect” to gain access to the debugger.

Safari — very similar to Chrome

As the picture states, in order to have access to the debugger, you must first click on “Safari” in the upper right corner of your screen and select Preferences. From there click on advanced and check the box that states “Show Develop menu in menu bar”. Once you do that you will be able to Right-click on the page and click on “inspect” to open the debugger.

Opera Dragonfly — Dragonfly is Opera’s built-in dev suite. Once separate from Opera, it is now included in the browser and offers a standard array of dev tools.

With Opera, F12 won't open the debugger. To open, right-click on your current page and click on “inspect”.

Microsoft Edge F12 — No longer lags behind Chrome and Firefox in terms of the debugger’s features.

Opening Microsoft Edge debugger is as simple as hitting F12 on your keyboard.

The most common debugging way in JavaScript is adding a console.log(this) to the object. Then go to the browser and choose the inspect. In the console, it will show all the properties in that object. If something goes wrong, you can easily find it. The image below is a demonstration in React.

Along with console.log, breakpoints are useful to help debug JavaScript. The keyword “debugger” will stop the JavaScript execution, allowing you to look at the current state of the program. The breakpoint only occurs if the console is open, otherwise, the debugger keyword is ignored. A simple example for client-side JavaScript:

Open the HTML file in a web browser. It should fully execute and render “Hello, world!” on the page. Activate the debugger keyword by opening the browser’s inspector and going to the sources tab, and then refresh the page. You should see something similar to this:

In the inspector, the line where the keyword was used is highlighted. The script is halted until you instruct the browser to continue. It is not a good practice to leave debugger keywords in your code. The end user may open their console, and this would stop the execution of the JavaScript on the webpage. However, the keyword is useful to stop a script and ensure it is behaving as expected while developing JavaScript.

Alternatively, event breakpoints can be set in most browsers’ inspectors. Let’s edit the example above to include a button that triggers “Hello world!” to be rendered on the page.

The addEventListener method is one way of programming an event listener in JavaScript. In this case, we’re programming what should occur on a “click” event with an anonymous function, which can be found in the second argument of the method.

We’ll need to set the event breakpoint in the browser’s debugger. In Chrome, this can be found in the Event Listener Breakpoints accordion section.

Open the “Mouse” portion, and check the “click” option. This will add a breakpoint anytime a click event occurs. Refresh the page and click the “Run the code!” button. There are many other events available to cause a breakpoint, and these can be activated without even looking at the code.

In Firefox, the process is slightly different. You simply select the lines where you’d like to apply a breakpoint. This is found under the Debugger tab in Firefox’s inspector.

When line 11 is executed, the breakpoint will occur. Generally, this is similar to how debugging works in IDEs for many programming languages. Which brings us to debugging server-side JavaScript. Although it is possible to debug server-side JavaScript using a browser, IDEs are arguably better suited for the job. For instance, there is an extension available for Visual Studio Code fittingly called “Node debug”. See Paige Niedringhaus’s article on using the extension. She also describes the various issues with debugging Node programs. Whichever environment you use, the best resource for most IDE debuggers is the software’s documentation.

UNIT TESTING FRAMEWORK

Unit testing is a software testing method that, as the name implies, allows you to test each individual part of your code such as functions, other types of subroutines, or a particular property. It ensures that those individual small parts work perfectly as expected. A unit testing framework helps you to perform this task by giving you the tools. There are some testing principles, the small components must be testable and isolated from the development environment.

Several unit testing frameworks exist for JavaScript, the following are among the most popular:

Jasmine — integrates well with many libraries but does not require any external libraries itself, comes with all the tools necessary to create unit tests. Allows you to run Node.js tests and browser tests in the same framework

Ava — minimalist testing framework, runs tests concurrently to increase performance. Also runs Node.js tests. No implicit globals needed like Mocha

Mocha — one of the most used frameworks, highly configurable to meet the developer’s needs

Karma — open source testing environment that allows you to run tests via the command line in your IDE and run tests on real devices, including phones, tablets, and even headless devices.

Jest — the testing framework used by Facebook, runs without configuration and attempts to make JavaScript testing as easy as possible.

We will demonstrate an example of a unit testing framework in action using Jest. Facebook usually uses it in conjunction with their JavaScript framework React, but we will show it testing JavaScript in a more general way. If you have been following our blog series, you may already have Node JS, but if you do not or was only following the client-side JavaScript you can download Node here https://nodejs.org/en/download/. Otherwise, you can begin by opening your command prompt or bash tool. Create a directory and navigate to it in your command prompt and use the command “npm init” (add -y if you prefer to use the default settings) to initialize your node modules. Afterwards, add jest to your directory using the following command:

You will notice a lot of things have been installed and added to your directory, including a dependency added to your package.json:

You will also notice that we changed our test script to automatically run Jest instead of the default error message echo.

Now that we have Jest installed, we can begin by creating two new files: a JavaScript file that will contain an arbitrary function that we will test and one file that shares the same name but with “test” for usage with the Jest framework.

Let’s begin coding. We will create an object named functions with a simple function that adds two numbers together and then we export the object to be used in our test file.

Afterwards, we will head to our test file. Begin by importing the object “functions” by using the “require” function and enter the following into your “functions.test.js” file:

After importing the functions object, you will use the test() function from the Jest framework to test whether our add() function that we have created earlier actually works as intended. The test() function will take in a string that acts as the name and a callback function that returns the result of the test. You can also add a third argument which acts as a timer, in milliseconds, for the test to timeout if it takes longer than the set limit. By running “npm test” in our console, we will run the script that will use jest to test our function.

Success! The console tells us that our addition function returns the expected answer from our inputted arguments. Now we will try to make our function fail. Switch back to our functions.js and add a small change.

If we now run Jest to test our code and not change anything from our “functions.test.js” file, we should expect our function to now output 5 instead of the expected 4. But how will Jest react to this change?

Now we have a lot more detail of the code we used earlier. The argument of expect is what Jest will receive from our function, and the argument of toBe() is what we expect the answer to be. Since we changed our function, what Jest receives is no longer the expected answer of 4 and the test will fail. Jest also pinpoints where our code fails. As you can see, it was in line 4. And that concludes our test of a method. The toBe function can take in the usual primitive types. For the falsy primitive, you can use toBeNull or toBeDefined and many more! Try some on your own, and remember: always check for bugs.

Authors:

Anh Le @anhle697

David Alvarado David Alvarado

Payne Wheat @PayneWheat

Shouchuang Zhu @shouchuangzhu

Will Pocklington @pocklingtonWill

UH COSC 4315 Group Project

A publication for COSC 4315

Will Pocklington

Written by

UH COSC 4315 Group Project

A publication for COSC 4315