What is Jasmine:
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:
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:
And finally the tests are imported
Following the head section, in the body you will just find few lines, responsible to actually run the rest:
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 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.
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.
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:
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.
And finally load spec.html and see the results:
Just for curiosity let’s change the second test to:
Now, the second test should fail:
And in fact it does!
To know more about jasmine click here.