Sunday, October 6, 2013

Basics of Jasmine Framework

Hey folks today we will look into some basics of jasmine. Jasmine is a behavior-driven testing framework for JavaScript programming language. It’s a bunch of tools that you can use to test JavaScript code. you can test your code against specifications that you write. If your code should work in a certain way, Jasmine helps you express
that intention in code.

Getting Started
1. Start by downloading the latest standalone release of Jasmine ( Unzip it.

2. In your html include scripts in following order:

<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script type="text/javascript" src="jasmine/lib/jasmine-core/boot.js"></script>

3. Now include you spec file. This is a normal js file in which your test cases are written. So in our case it will be

<!-- Spec files-->
<script type="text/javascript" src="spec/calculatorSpec.js"></script>

Please not that always include spec file before actual code file.

4. Now we include the code file

<!-- Src files-->
<script type="text/javascript" src="src/calculator.js"></script>

Which will contain our logic

Now here are few things you need to know before we look into the code of spec file

* A describe("some name"...) is called a suite. This name of suite would usually be a component of your application.
* Inside of suite is the it() block. This is called specification. Its is a Js function that says what a small  peice of your component must do.

* Matchers: This basically takes the arguement to the expect function and checks to see if it satisfies some criterion in the matcher. for example: toEqual()

Now lets take a look at the spec

You can view the example here:

We are carrying out five tests here:
1. Storing current value
2. Addition yields correct results. 
3. Substraction yields correct results.
4. Multiplication yields correct results.
5. Division yields correct results.

Here is the code for spec file:

it("Should have current value stored",function(){
calculator.currentValue = 0
describe("Addition module",function(){
it("Should add two numbers",function(){
describe("Substraction module",function(){
it("Should substract two numbers",function(){
describe("Multiplication module",function(){
it("Should multiply two numbers",function(){
calculator.currentValue = 5;
describe("Division module",function(){
it("Should divide two numbers",function(){

Here is the corresponding code for calculator.js code

var calculator = {
currentValue : 0,
add: function(num){
return this.currentValue += num;
return this.currentValue -= num;
return this.currentValue *= num;
return 25/num;

Hope this article was useful. For any queries write me at

No comments:

Post a Comment