Jasmine Test Cases-Part 1: Unit testing JavaScript in Phonegap Application


For PhoneGap applications, we can write unit tests that evaluate our JavaScript logic to verify proper behavior in our apps using a number of tools, but these only test JS execution and logic.

In this blog, I discuss some of the basics for writing JavaScript unit tests using Jasmine. Then, you can apply that information to writing and running JavaScript unit tests with Jasmine.

What is Jasmine:

Jasmine is a behavior-driven development (BDD) JavaScript testing framework. Pivotal Labs maintains it and makes it available on GitHub under the MIT license. Jasmine allows tests to be written independent of the DOM or other JavaScript frameworks. And it has a clean, obvious syntax so that you can easily write tests. Jasmine is an open source testing framework for JavaScript. It aims to run on any JavaScript-enabled platform, to not intrude on the application nor the IDE, and to have easy-to-read syntax.
Jasmine has a number of other features, such as custom matchers, spies, and support for asynchronous specifications.

Setting up jasmine in Phonegap Application:

Clone the project from here or download the zip, and unpacked in some folder you will find a folder called spec and  a file called spec.html. This is the file containing everything we need to setup Jasmine and get started with testing.
Let’s have a closer look:


<link rel="stylesheet" type="text/css" href="spec/lib/jasmine-1.2.0/jasmine.css">
<script type="text/javascript" src="spec/lib/jasmine-1.2.0/jasmine.js"></script>
<script type="text/javascript" src="spec/lib/jasmine-1.2.0/jasmine-html.js"></script>
<script type="text/javascript" src="spec/lib/jasmine-1.2.0/jasmine-jquery.js"></script>

This basically imports Jasmine itself with relative css to make the result’s report looking prettier. It includes all required jasmine js file, that needs to test jquery and html code.

Then we find the files containing the code we want to test, which placed in the js folder:

<script type="text/javascript" src="js/index.js"></script>

And finally the tests are imported

<script type="text/javascript" src="spec/helper.js"></script>
<script type="text/javascript" src="spec/index.js"></script>

Following the head section, in the body you will just find few lines, responsible to actually run the rest:

<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};

var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>

Jasmine Test Syntax:

To create a suite of tests we basically need 2 functions:
- describe(): groups tests together providing also setup and teardown hooks.
- it(): contains the test itself

Suites: describe Tests:

A test suite begins with a call to the global Jasmine function describe with two parameters: a string and a function. The string is a name or title for a spec suite – usually what is under test. The function is a block of code that implements the suite.

Specs:

Specs are defined by calling the global Jasmine function it, which, like describe takes a string and a function. The string is a title for this spec and the function is the spec, or test. A spec contains one or more expectations that test the state of the code under test.

Expectation:

An expectation in Jasmine is an assertion that can be either true or false. A spec with all true expectations is a passing spec. A spec with one or more expectations that evaluate to false is a failing spec. Expectations are built with the function expect which takes a value, called the actual. It is chained with a Matcher function, which takes the expected value.

Syntax:

describe('Hello world', function() {
it('says hello', function() {
expect(helloWorld()).toEqual("Hello world!");
});
});

So let’s write a simple unit test for a function validating an email address. Let’s write the tests first.
Edit a file under the spec folder called index.js, with:

describe("Email validation", function() {

it("should validate info@knoldus.com",function(){
var result = isEmail_valid("info@knoldus.com");
expect(result).toBe(true);
});

it("should not validate info@knoldus",function(){
var result = isEmail_valid("info@knoldus");
expect(result).not.toBe(true);
});
});

As you can see I used one of the built in expectations called toBe() with the relative not.toBe(), which is the logical not. It checks the return value from the isEmail_valid() function.

function isEmail_valid(email){
var pattern =/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
return pattern.test(email)
};

And finally load spec.html and see the results:

Selection_001

Just for curiosity let’s change the second test to:

it("should not validate info@knoldus",function(){
var result = isEmail_valid("info@knoldus");
expect(result).toBe(true);
});
});

Now, the second test should fail:

Selection_002

And in fact it does!

To know more about jasmine click here.

About Ruchi Agarwal

Software Consultant at Knoldus Software LLP having around 2 year experience working in Scala and java. She has good understanding of various technologies like LiftWeb, Akka, Amazon EC2, jQuery, javascript, CSS etc. She is RAD (Rational Application Developer) for WebSphere Software and RFT (Rational Funtional Tester) for Java certified. She is a skilled professional focused on the basic business functions and creation of software. She has a firm understanding of design methodology. She likes to work with responsibility, dedication and perseverance, she has a facility to establish good interpersonal relationships and foremost she is loyal to her principles, ethics and always giving to the best of her caliber.
This entry was posted in Web and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s