How to perform unit testing in AngularJS



Image not found!!

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:

  1. Setup Testing Environment:

    • Install Jasmine: If you haven't already, install Jasmine using npm:
      css
      npm install jasmine --save-dev
    • Initialize Jasmine: Set up Jasmine by running:
      bash
      ./node_modules/jasmine/bin/jasmine init

    This will create a spec directory where your test files will reside.

  2. Write Test Cases:

    • Create a test file: Inside the 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.
    • Write test cases: In your test file, write test cases using Jasmine's syntax. Test the behavior of your AngularJS components like controllers, services, etc. For example:
      javascript
      describe('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); }); });
  3. Run Tests:

    • Run tests: Run your tests using the Jasmine CLI:
      bash
      ./node_modules/jasmine/bin/jasmine
  4. Mock Dependencies:

    • Use mock dependencies: Use AngularJS's $provide service or Jasmine's spies to mock dependencies like services, $httpBackend, etc., to isolate your components during testing.
  5. Coverage Reporting:

    • Generate coverage reports: You can use tools like Istanbul or Karma coverage to generate code coverage reports for your tests.
  6. Other Considerations:

    • Use $rootScope.$apply(): In tests involving asynchronous operations or promises, use $rootScope.$apply() to resolve promises and trigger watchers.
  7. Continuous Integration:

    • Integrate with CI/CD pipelines: Incorporate your unit tests into your Continuous Integration/Continuous Deployment pipelines to ensure code quality and prevent regressions.

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.