Unit testing in AngularJS can be accomplished using testing frameworks like Jasmine or Mocha along with testing utilities provided by AngularJS itself. Here's a basic guide on how to perform unit testing in AngularJS using Jasmine as the testing framework:
Setup Testing Environment:
cssnpm install jasmine --save-dev
bash./node_modules/jasmine/bin/jasmine init
This will create a spec
directory where your test files will reside.
Write Test Cases:
spec
directory, create a test file for your AngularJS component. For example, if you're testing a controller named MyController
, create a file named myController.spec.js
.javascriptdescribe('MyController', function() {
beforeEach(module('myApp')); // Assuming 'myApp' is your AngularJS module name
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
it('should have initial value of 5', function() {
var $scope = {};
var controller = $controller('MyController', { $scope: $scope });
expect($scope.value).toEqual(5);
});
});
Run Tests:
bash./node_modules/jasmine/bin/jasmine
Mock Dependencies:
$provide
service or Jasmine's spies to mock dependencies like services, $httpBackend, etc., to isolate your components during testing.Coverage Reporting:
Other Considerations:
$rootScope.$apply()
: In tests involving asynchronous operations or promises, use $rootScope.$apply()
to resolve promises and trigger watchers.Continuous Integration:
Remember, this is a basic guide, and you might need to adjust the process based on your specific project setup and requirements. Additionally, AngularJS has evolved, and if you're using newer versions like Angular (2+), the testing process might differ slightly.