The Unit Testing process involves the smallest atomic parts of an application (called "units") and a battery of tests, these units are individually inspected to verify they work properly. By repeating this process continually during the development cycle, we can assure the quality of the product.
If you want to modify the configuration of the Unit Test framework, go to the next page of the wizard and click on Test Library:
Otherwise click Finish, this will create the new project and the required files will be automatically copied to the project:
Now that we have the project, we will need 3 things:
- A function to test.
- A Jasmine Spec File.
- A Jasmine Spec Runner.
Now we will create the Jasmine Spec File, to do this, right click the project > New > Jasmine Spec File, enter “MultiplySpec” as the file name and select the tests folder to create the new file in that location:
Click Next. In this page of the wizard you can select the file that contains the function we want to test, in this case the Multiply.js file we created before:
Click Finish, this will create the skeleton of the test:
We need to modify this code, to actually test the function:
As you can see, we have three tests (defined by the it function), in the last one we are passing a string to the Multiply() function, therefore this test will fail as it expects only numbers.
Finally, we will create the Jasmine Spec Runner, this file is used to run the tests in the server. To create this file, right click the project > New > Web Page, select Jasmine Spec Runner from the Templates list, then click on the Options… button.
Both files will be added to the list:
This view contains information about the results of the tests, in this case, the progress bar is red, meaning that, one or more tests failed, at the top-left corner you have the total executing time, right below, the overall execution status is displayed. At the bottom left, you can quickly identify which tests passed or failed by looking at the icons, in this case, the last test failed, so, if you click the failed tests, the Failure Trace section will be populated with the stack trace of the problem:
You can double click on the entries in the stack trace to open the associated files.
Once you have found and fix all the problem, the view will look like this:
A green progress bar indicates no errors were detected.
How to integrate Code Coverage?
When should you perform unit tests?
Short answer, as often as possible. Long answer, as writing unit tests might be a time-consuming process it is not easy to prepare a good battery of tests, but in the long run, the benefits overcome the problems, i.e:
- Problems are detected early in the development cycle.
- Write code that is easy to test.
- Confidence in the finished product.
- Making sure that new functionality doesn’t break the existing one.
Ultimately, all this benefits point to the same goal, to increase the quality of the applications.