Monday, March 23, 2015

Installing Mocha, Karma, and setting up Unit Tests

Today we worked a lot on setting up unit testing. While it could be done in Javascript, there's a lot of tools available that allow the process to be done more quickly and efficiently. We decided to use Mocha and Karma. The setup was simple, however I ran into a lot of issues, so I decided to make a shell script that will automate the process for anyone on a Mac with Homebrew. Comments are included so that anyone knows what it is doing.

# I was installing Mocha and Karma on a Mac, so you're going to need Homebrew.
brew install npm
# I installed NPM, the package manager that allowed me to install Mocha, and later Karma.
npm install -g mocha
# I installed Mocha globally
npm install karma --save-dev
npm install karma-jasmine karma-chrome-launcher --save-dev
# I installed Karma globally - note: do not run this from the directory it's installing to - it will have errors
#./node_modules/karma/bin/karma start
# I could have started it with the code above. But, I'd like that to be easier.
# There's an option to install a command line interface, so I did that as well
npm install -g karma-cli
# Now we run Karma
karma
view raw gistfile1.sh hosted with ❤ by GitHub

After some research, we got Mocha working. We created a /tests/ directory on our GitHub repo, which we use to create and test working code. Our first test function, stripHTMLTags, isn't working yet, because we are still working with issues related to Mocha detecting our window variable from Firefox OS. A fix will hopefully come tomorrow.

The function so far looks like this.

It can be tested by using the following code:

mocha . -r "js/app"

Mocha . runs all tests in the directory you're in, so you have to be in the tests/ directory. -r is equivalent to "require", which is a function that tells the test what Javascript file you're testing. For some reason, using require("js/app") as a function in our test isn't working. It's likely due to a directory structure issue.

We also are awaiting an email response as to what we can use Karma for. Hopefully a response will come tomorrow, but otherwise we can always do some more research. Tests will start tomorrow, since our setup is done.

No comments:

Post a Comment