Up until now, I have mostly been coding in JavaScript, Ruby, and Python. But recently, I had to do a coding challenge in C#, which is relatively unlike those languages and has more in common with languages like C, C++, and Java. Unfortunately I did not get that position, but I got a good introduction to C# along the way and an insight into a new kind of programming language.
I have been using the Mocha framework to test the frontend of a web app that I created with JavaScript, Tibetan Monastery Gazetteer. Unit testing in Mocha is quite similar to RSpec testing for Ruby, as the principles of testing are the same regardless of the language. My app poses some challenges as far as testing is concerned. Although much of my code controls the appearance of a web page, Mocha is designed for a Node.js environment, so it does not has access to the DOM without addons. One approach is to set up Mocha to be run in the browser, but there are workarounds so that you can use to test the DOM functionality in the command line. A second challenge is that some of the app’s functionality is asynchronous, and so is the functionality that can load an HTML file into Mocha.
In previous posts I talked about testing Ruby code in RSpec. What if you want to test your JavaScript code? The most common framework for JavaScript testing is Mocha. As we will see, the syntax is quite similar to RSpec and other testing frameworks. The differences primarily involve the syntactic features of JavaScript.
In my last blog post, I explained how to test your Ruby code with RSpec. In this post, I will provide an example of testing in action, based on my Ruby command line project Music Explorer (which interfaces with the Spotify API to browse music artists and associated information). This was the first project for Flatiron School and I chose it to demonstrate testing because it is a relatively simple application, using a single language Ruby, and not incorporating a complex frameworks like Rails.
Most of programming is about getting your code to work properly. New programmers often just write a bunch of code, play with while running the code, and then try to find the bugs (perhaps using some debugging tools in the process). But this is a haphazard approach, and it can miss some edge cases, or result in complex bugs that is difficult to trace to a specific piece of code. A better approach is to write unit tests using a testing suite, testing each function and method to make sure it works as expected. (Even better is test driven development: write the tests first, and then write code to make them work. This post, however, is focused on how to write tests, and I will save TDD for a future post.) Testing not only makes debugging simpler and more effective, it is also a skill highly sought after by employers in the tech field, something you often need to know to get a developer job.