Writing and testing unit test cases is an important part of ensuring the code that we write are bug free. If you look into the Jasmine folder, you will find the following file and folders:
Lib – This folder contains Jasmine library files
Spec – This folder contains spec files, i.e. test case files
Src – This folder contains source files
SpecRunner.html – This file helps to run unit test cases by including ‘Spec’, ‘src’ folders and configuring Jasmine run time.
You can download Jasmine folder from https://github.com/pivotal/jasmine/tree/master/dist
In following figure describes you the same:
You can create sub-folders in ‘spec’ and ‘src’ to organize your source and spec files. Further, for ease of testing, you can duplicate ‘SpecRunner.html’ and can include your source and spec files. Now you can run ‘SpecRunner.html’ in your favorite browser to verify your test cases.
Karma (formerly known as Testacular) is a test runner that makes unit testing easy and fun at client-side. Main goal of Karma is to provide productive testing environment to developers.
We need to follow the below mentioned steps to install and configure Karma:
For installing Karma using Node package manager (npm), first need to have Node.js to be installed in your machine. You can get Node.js installer from http://nodejs.org/.
After you have installed Node.js, go to your terminal or command line and type
npm install –g karma-cli
This will put the karma command in your system path, allowing it to be run from any directory.
For configuring Karma, let’s navigate to that directory and type the following command:
Karma init karma.config.js
For the above example,
You will be asked following questions during this process:
- Testing framework you want to use
- Whether you want the files to be watched
- What files to include
For our article, we’ll leave ‘jasmine’ as the default framework, let it autowatch files.
Now you are ready to start Karma. Again from the terminal type:
|karma start karma.config.js|
In the following video, let’s go through the above steps:
After Chrome browser gets opened, you can look at the terminal (command prompt) to see that all the test cases got pass. Now come to your editor and make some changes in your spec or source file, e.g let a test case fail. If you go back and check your terminal you will get the failed notification.
So, making changes will run the test cases automatically.