posted on 10/24/12 at 04:24:06 pm by Joel Ross
To get started, I wanted to do something simple, so I did a couple of Katas. Doing a kata was nice because the code I was writing didn't have any external dependencies (like the DOM), and it allowed me to focus solely on learning Jasmine.
Getting started with Jasmine isn't all that difficult. First, you create a simple HTML file that will act as your test runner. You need to include references to a few Jasmine files, your class under test, and your tests. Then you fire up the Jasmine environment and run the tests.
For simplicity, the file looks like I have all of the files in one directory. The actual repository is organized a little bit better than that.
The Kata I chose was FizzBuzz, since it's a pretty simple one and I wouldn't get bogged down in the code. My first spec looked like this:
You start each test with a call to describe, giving a description and a function for what this will test. You can have a setup method (beforeEach()) that will handle any set up, and you can nest describe calls to handle more set up. The heart of the test is the It() method, because this is where you verify your results. In the method above, I'm validating that if you pass in 1, you get the string representation of it back.
The documentation for Jasmine is very good, and goes over all the different ways you can set up expectations, so I won't touch on that here - they say it much better than I could.
Back to our example. Without any implementation, I ran the specs to see what I got.
One test and two failures. That sounds like success to me! But I thought a passing test would be a bit better, so I added a simple class that lets the test pass.
Rerunning the test now reflects that.
I then went ahead and finished out the tests and the implementation (available in my Jasmine repo on GitHub). When done, I ended up with six tests that all passed.
Like I said, it's a fairly simple exercise, but it definitely gave me a feel for what Jasmine could do. Next up was to try it against a real world example, but I'll save that for another post.