Unit Testing of Javascript Functions
Introduction
This article is all about Unit Testing of Javascript functions using unittest.js library provided by Script.aculo.us.
We always use UI and test against , this is how the DEV or QA folks do. But there is some thing which can be done by DEV apart from that. We can do Unit Test the Java Script functions without the UI getting ready. Which means one can completely test the Java script functions at early stage.
All you have to do is Just follow 3 Step mentioned in the article , you will surely enjoying doing Unit Testing.
Using the code
Following are the steps for Downloading Script.aculo.us
1. Go to the http://script.aculo.us/downloads to grab the latest version in a convenient package.
2. Unpack downloaded file and you will find following files:
- 1. builder.js
- 2. controls.js
- 3. dragdrop.js
- 4. effects.js
- 5. scriptaculous.js
- 6. slider.js
- 7. sound.js
- 8. unittest.js
lib : This folder is having prototype.js file.
src: This folder is having 8 files
test (folder): having files for testing purpose.
How to use?
All we require is unittest.js, style sheet test.css available in the downloaded folders.
1. Create a JavaScript file which contains functions which you wish to do Unit Test.
var Validator = { // Returns the string, or null if not a valid email email: function (str) { str = str.squash(); var result = (/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i).exec(str); return (result) ? result[0] : null; } };
2. Create a Unit Test JavaScript class
new Test.Unit.Runner({ testValidator: function () { this.assertNull(Validator.email(' ranjancse@gmail.com ')); this.assertNull(Validator.email(' roshancse@gmail.com ')); });
The Test.Unit.Runner object receives our test object, and executes all the methods. In our case there is only one method for testing. Each of test method performs a series of checks, called assertions, to ensure that our code works correctly.
There exists good number of assert methods available in the JavaScript library unittest.js , Just try to explore and use them.
3. Create a sample HTML page and include the following scripts
- unittest.js - Framework library provided by Script.aculo.us
- Experniment.js - We have created this one, which contains the javascript functions
- test.js - We have created this one, which contains Unit Test methods. One can add as many unit tests they wish.
We are creating a DIV with id=’testlog’ which will be used by unit test library to fill the Test results. We are including the style sheet test.css, it contains styles to show the Test results more colorful.
Points of Interest
I always feel it is good to do unit testing of Javascript functions
Unit Test Result
发表评论
vrpEBA Appreciate you sharing, great blog article. Cool.