Testing with Jasmine
You are writing a simple calculator using CoffeeScript and you want to verify it functions as expected. You decide to use the Jasmine test framework.
When using the Jasmine test framework, you write tests in a specification (spec) file that describes the expected functionality of the code to be tested.
For example, we expect our calculator will be able to add and subtract and will function correctly with both positive and negative numbers. Our spec is listed below.
Before you can run your tests, you must download and configure Jasmine. This involves:
- downloading the latest Jasmine zip file;
- creating a spec and a spec/jasmine folder in your project;
- extracting the downloaded Jasmine files into the spec/jasmine folder; and
- creating a test runner.
Create a Test Runner
This spec runner can be downloaded from this GitHub gist.
In the above example, we include our yet-to-be-developed calculator.js file on line 14 and our compiled calculatorSpec.js file on line 17.
Running the Tests
To run our tests, simply open SpecRunner.html in a web browser. In our example we see 4 failing specs with a total of 8 failures (below).
It appears our tests are failing because Jasmine cannot find the variable Calculator. That’s because it has not been created yet. Let’s do that now by creating a new file named js/calculator.coffee.
Compile calculator.coffee and refresh the browser to re-run the test suite.
We now have 4 failures instead of our previous 8. That’s a 50% improvement with only one line of code.
Getting the Tests to Pass
Let’s implement our methods and see if we can get these tests to pass.
When we refresh we see they all pass.
Refactoring the Tests
Now that our tests pass, we should look to see if our code or our test(s) can be refactored.
In our spec file, each test creates its own calculator instance. This can make our tests quite repetitive especially for larger test suites. Ideally, we should consider moving that initialization code into a routine that runs before each test.
Luckily Jasmine has a beforeEach function just for this purpose.
When we recompile our spec and refresh the browser we see the tests still all pass.