AngularJS has grown to become one of the most popular open-source web application frameworks, developed by a dedicated team at Google to address the challenges encountered in developing single-page-applications.
Sample code for unit testing with jasmine:
In the above example we come across suite, specs and predefined matchers. Let’s have a look at it.
Suites and specs:
A Suite represents a bunch of tests that are related. Each suite in turn contains a set of Expectations that compare the results of the test with the actual and the expected value.
- A Suite is defined by calling the describe()
- It takes two parameters: the name of the Suite, and the function which contains the calls to the expectation methods called Specs.
Specs are defined using the it() method. It also takes two parameters like describe(),a name and function parameter. The it() function parameter may contain variables and one or more calls to the expect() method which is used in conjunction with a Matcher function, for comparing the actual and expected values.
In the above example, the toEqual() method is a matcher. It represents the regular equality (==) operator.
As controllers are not available on the global scope, we use angular.mock.inject to inject our controller first. Then we pass module information into beforeEach, a function where Jasmine lets us run code before each test. Then we can use inject to access $controller the service that is responsible for instantiating controllers.
Filters in angularjs are used to format the data.
Unit testing becomes tricky at times, but it is worth spending the time on it as it ensures the correctness of the application. AngularJS makes it easier to unit test the code written using the framework.
I would like to hear your thoughts , Feel free to leave comments.
Have a great day!