Sunday, April 28, 2019

TDD in JavaScript (Part 1)

This blog post was originally published on the ThoroughTest website, back when that was a thing. As a co-founder and primary content contributor for ThoroughTest, I absolutely own the rights to this post and the source code to which it refers. I intend to reproduce each blog post here on my personal blog since the company is no longer in business.


We've heard from some front-end developers that test-driven development isn't possible or useful for them. We (obviously) couldn't disagree more so we decided to put together a quick guide to using test-driven development to create a pure JavaScript application. We prefer the Jasmine testing framework so that's what we're going to demonstrate here.

First off, if this is the first time you've heard of Jasmine you might want to check out their official site (the link is in the Resources section at the bottom of this post).

Whether you want to check out their site or not, you're going to need to go there to get the framework. Don't worry, it's a small download and they have it available in .zip and .tar format. You can just go straight to the link in the Resources section if you don't want to browse their site.

To keep things simple I created a directory called "tddjs" on my desktop and unzipped the file I downloaded straight into that directory. Here's what my folder looks like.


Their download now includes some sample code of their own (in the src and spec folders), but we don't need that. For this guide we are only interested in keeping the contents of the lib/jasmine-2.8.0 directory and the SpecRunner.html file in the root. I'm going to go ahead and delete the other files. Here's what my folder looks like now.

Looking into the lib/jasmine-2.8.0 folder we see 6 files:

boot.js

console.js

jasmine.css

jasmine.js

jasmine-favicon.png

jasmine-html.js

jasmine.js contains the actual Jasmine testing framework, jasmine-html.js contains some functions that help format the page, and boot.js initializes Jasmine.

Now that we have Jasmine ready we need some code to test. *record scratch* Oops. We need some tests. We're going to create a simple tic-tac-toe game. This should allow us to focus on the functionality we expect instead of getting bogged down in how things look. This is actually a really good stopping point so we're going to break here. We should be able to wrap things up in our next post.

Resources

Official Jasmine Home Page

Download Jasmine


No comments:

Post a Comment