The Ultimate AngularJS Testing Guide

Test AngularJS apps efficiently on real devices and browsers with BrowserStack, seamless automation and instant cross-browser coverage.

Get Started free
Home Guide The Ultimate AngularJS Testing Guide

The Ultimate AngularJS Testing Guide

AngularJS is used widely in production by several top companies such as Google, Microsoft, and NASA. It incorporates reusable component-based development, saving a lot of time.

Overview

Importance of AngularJS Testing:

AngularJS testing ensures app reliability and smooth user experience by catching issues early and maintaining code quality. Automated testing boosts efficiency and consistency in development.

How to Perform AngularJS Testing:

  1. Its modular design and dependency injection make unit testing straightforward.
  2. Manual testing is good for exploratory checks; automation suits regression and CI/CD.
  3. Use Jasmine for unit tests, Karma to execute them, and Cypress or NightwatchJS for E2E tests.
  4. Leverage angular-mocks to simulate services and components during tests.
  5. Automate tests for faster feedback and consistent quality.

This article discusses effective strategies and tools for AngularJS testing to help build stable, maintainable applications.

What is AngularJS?

AngularJS is an open-source JavaScript framework developed by Google for building dynamic, single-page web applications (SPAs).

It enhances HTML with declarative syntax and supports features like two-way data binding, dependency injection, and modular architecture.

These capabilities make it easier to develop interactive and maintainable front-end applications. While newer frameworks have emerged, AngularJS remains used for many legacy projects, where structured architecture and built-in testing support continue to offer value.

Importance of AngularJS Testing

Testing is essential in AngularJS applications to maintain performance, reduce bugs, and ensure smooth user experiences, particularly as applications grow in complexity or evolve.

Key reasons why AngularJS testing is important:

  • Ensures reliability of dynamic UI: AngularJS apps rely on two-way data binding and real-time UI updates. Testing ensures these interactions behave correctly across scenarios.
  • Validates business logic: Unit testing helps confirm that individual components, controllers, services, and filters perform expected logic and calculations.
  • Speeds up development cycles: Automated testing allows developers to catch regressions early and iterate faster without breaking existing functionality.
  • Improves code maintainability: Well-tested code is easier to refactor, debug, and extend, reducing technical debt in large AngularJS codebases.
  • Supports long-term legacy maintenance: Many enterprise apps still run on AngularJS. Testing ensures these apps remain stable despite framework age or evolving requirements.

How to Perform AngularJS testing?

AngularJS supports manual and automated testing, with most teams opting for automation to achieve efficiency and consistency.

Here’s how you can approach AngularJS testing effectively:

  • Designed for testability: AngularJS’s architecture promotes clean separation of concerns and dependency injection, making unit testing straightforward and maintainable.
  • Choose between manual and automated testing: Manual testing is time-intensive and best suited for exploratory or UI feedback. Automated testing is faster and better aligned with CI/CD workflows.
  • Automate with the right tools: Use tools like Jasmine for writing unit test specs, Karma for running tests, and Cypress or NightwatchJS for end-to-end testing.
  • Leverage helper modules: Use angular-mocks to simulate services and components during testing without affecting real data or behavior.
  • Run tests at scale with BrowserStack: Cloud-based platforms like BrowserStack allow developers to test AngularJS apps across multiple browsers and OS combinations using real devices, without local infrastructure.

Try BrowserStack Now

Tools used for AngularJS Testing

Automating tests increases their effectiveness compared to manual tests. Automated tests have wide test coverage and better speed while testing AngularJS applications. They do not require human intervention and are cheaper than manual testing.

Tools used for AngularJS Testing:

  1. Karma: Test runner that executes JavaScript tests in real browsers.
  2. Jasmine: Behavior-driven framework for writing clear and readable test cases.
  3. Protractor: Deprecated E2E testing tool designed specifically for Angular apps.
  4. Cypress: Modern E2E testing tool offering fast, reliable browser automation.
  5. angular-mocks (ngMock): This module provides mock services and testing utilities for AngularJS.

Here is a description of these tools that can be used while running automated tests in AngularJS applications.

Karma

Karma is an automated testing tool that was created by the AngularJS team at Google itself. Karma is often mistaken to be considered a framework or an assertion library. However, it is a test runner tool that allows running test cases inside various browsers through the command line.

Karma rolls out directly from the Angular team, as a result of which it has become the default test runner for applications created with Angular CLI. Karma also offers easy integration of testing frameworks and services.

Karma offers several advantages, such as being open-source and backed by Google. Karma being backed by a tech giant builds trust among the users and automatically encourages good community support.

Creating a Test Environment

Now, let us learn to install Karma.

Step 1: Install Karma, Karma launcher, and Jasmine which is the dependent framework for karma via npm.

npm install karma karma-chrome-launcher karma-jasmine

Step 2: Now, install the Karma CLI utility that will be required to initialize the Karma environment for testing.

npm install karma-cli

Step 3: Configure Karma via the command

karma -init

Jasmine

Jasmine is a BDD testing framework for the purpose of testing JavaScript code and integrates very well with Karma. In the official documentation of Angular, Jasmine and Karma are both recommended as testing frameworks.

Jasmine provides an extension known as Jasmine-jQuery, which eases front-end testing. Moreover, Jasmine has an easy syntax, which is quite readable and maintainable.

The biggest advantage of using Jasmine is it is highly compatible with numerous libraries and frameworks. Moreover, it has a strong community and an easy learning curve. However, one major drawback of using Jasmine is that it will require several configurations before selecting any assertion library. Also, the user has to use a mocking framework before using Jasmine.

Creating a Test Environment

Step 1: Install npm modules

npm install jasmine-node

Step 2: Initialize the Jasmine Environment 

jasmine init

Step 3: Initialize the configuration file 

The configuration JSON file will be stored in the spec/support folder. By default, it is named as jasmine.json.

Protractor

Protractor is an open-source testing framework for AngularJS that comes in handy in combining popular technologies such as Mocha, Jasmine, Selenium, and more. Initially, it was developed by Google Engineers to support Angular testing.

However, later it was released as an open-source framework. The protractor wraps over all the features of Selenium WebDriver and Angular-specific features. Protractor supports both Angular and Non-angular features, which broadens the scope of testing, offering end-to-end testing features for the entire application, even if has non-angular components.

Protractor makes it easy to run image comparisons and also runs on top of the Selenium web driver. Hence, Protractor supports all the capabilities of a web driver.

Some drawbacks of using Protractor are there such as it supports only JavaScript, limited browser support, and the absence of a Robot class in Protector.

Creating a Test Environment

Step 1: Install Protractor globally via npm

npm install -g protractor

Step 2: Check Protractor is installed

Follow the command to check if Protractor is installed.

protractor -version

Step 3: Update the web driver manager

webdriver-manager update

Step 4: Start the WebDriver manager

Once the web driver is started, it will automatically load and run the tests in the relevant browser.

webdriver-manager start

It is important to note that Protractor has been deprecated.NightwatchJS is an effective Protractor alternative maintained by BrowserStack that can automate tests.

Cypress

Cypress is an end-to-end testing framework that is not limited entirely to Angular. Cypress is a full-fledged JavaScript framework that states you could start writing tests right after installing it in your system.

Cypress is built on a new architecture and runs in the same loop as the application being tested, which makes it fast, reliable, and convenient. Moreover, Cypress provides several bundled packages such as Mocha, Chai, and Sinon.

While installing Cypress, it does not require any additional downloads or dependencies. However, Cypress only supports JavaScript testing and is not very well suited for cross-browser testing.

Creating a Test Environment

Step 1: Initialize the project

npm init

Step 2: Install Cypress via npm 

npm install cypress --save-dev

Angular mocks (ngMock)

The angular-mocks module, called ngMock, is an essential AngularJS testing utility that simplifies unit testing by providing helper methods to inject dependencies and mock AngularJS components.

By mocking services, controllers, and modules, testers can create isolated test environments, ensuring tests focus on individual units without external interference.

Key features include:

  • The $controller service is used to create controllers with fake (mocked) dependencies for testing.
  • The inject() function to retrieve and inject services or components into test cases.
  • Mocking HTTP requests using $httpBackend to simulate backend responses.

Here’s a brief example demonstrating how to use angular-mocks (ngMock) for unit testing an AngularJS controller:

describe('MyController', function() {

  var $controller, $rootScope, $scope;



  // Load the module that contains the controller

  beforeEach(module('myApp'));



  // Inject angular-mocks services

  beforeEach(inject(function(_$controller_, _$rootScope_) {

    $controller = _$controller_;

    $rootScope = _$rootScope_;

    $scope = $rootScope.$new();

  }));



  it('should initialize the scope variable correctly', function() {

    // Instantiate the controller with the new scope

    var controller = $controller('MyController', { $scope: $scope });



    // Test the expected behavior

    expect($scope.title).toBe('Hello AngularJS');

  });

});

Explanation:

  • module(‘myApp’) loads the AngularJS app module.
  • inject() injects $controller and $rootScope from ngMock.
  • $controller creates an instance of the controller with a fresh scope.
  • The test checks if the controller initializes $scope.title correctly.

Testing AngularJS Controllers

A controller is a JavaScript Object that controls the data of AngularJS applications. The ng-controller directive defines the application controller.

This section will test controllers with the ability of the Karma testing framework.

Step 1: Install Angular.Js mocks library via npm

npm install Angular JS-mocks

Step 2: Modify configuration file 

In the Karma configuration file, karma.conf.js mention the Karma files must include for testing.

files: ['lib/AngularJS.js','lib/AngularJS-mocks.js','lib/index.js','test/*.js']

Step 3: Create a sample AngularJS application 

In the test folder of the application, paste the following code inside the index.js file.

var sampleApp = AngularJS.module('sampleApp',[]);
sampleApp.controller('AngularJSController', function($scope) {
$scope.ID =1;
});

Step 4: Write test case

In the test folder, paste the following code inside ControllerTest.js file.

describe('AngularJSController', function() {
beforeEach(module('sampleApp'));

var $controller;

beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));

describe('$scope.ID', function() {
it('Check the scope object', function() {
var $scope = {};
var controller = $controller('AngularJSController', { $scope: $scope });
expect($scope.ID).toEqual(1);
});
});
});

Upon executing, the test will run in the Karma browser.

Testing AngularJS Services

Services in AngularJS encapsulate business logic, making them ideal candidates for unit testing. Testing services ensure your core logic functions correctly and independently of controllers or views.

Why and How to Unit Test Services

  • Services typically contain reusable logic like API calls, data processing, or configuration management.
  • Unit testing ensures this logic behaves correctly in isolation, making your application more robust.
  • Use tools like Jasmine for assertions and angular-mocks to inject dependencies and mock external modules or services.
  • Set up the test environment by testing each function within the service individually using the inject() and beforeEach() methods.

Example: Unit Testing an AngularJS Service

Here’s a simple example of how to test a service using angular-mocks and Jasmine:

angular.module('app', []).service('MathService', function() {

  this.add = function(a, b) {

    return a + b;

  };

});



// Unit Test

describe('MathService', function() {

  var MathService;



  beforeEach(module('app'));

  beforeEach(inject(function(_MathService_) {

    MathService = _MathService_;

  }));



  it('should add two numbers correctly', function() {

    expect(MathService.add(2, 3)).toEqual(5);

  });

});

This test isolates the MathService and validates that its add() method returns the correct sum. By using angular-mocks, we simulate the AngularJS dependency injection system, ensuring realistic test conditions without needing a full application runtime.

Testing AngularJS directives

Directives in Angular are the classes used to modify the previous behavior of the elements in the template. It could be achieved by adding new elements, removing old elements, or even changing the appearance of the elements in the DOM.

Step 1: Install Angular.Js mocks library via npm

npm install Angular JS-mocks

Step 2: Modify configuration file 

In the Karma configuration file, karma.conf.js mention the Karma files must include for testing.

files: ['lib/AngularJS.js','lib/AngularJS-mocks.js','lib/index.js','test/*.js']

Step 3: Create a sample AngularJS application 

var sampleApp = AngularJS.module('sampleApp',[]);
sampleApp.directive('BrowserStack', function () {
return {
restrict: 'E',
replace: true,
template: '<p>AngularJS testing</p>'
};
});

Step 4: Write a test case

describe('Unit testing directives', function() {
var $compile,
$rootScope;
beforeEach(module('sampleApp'));

beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));

it('Check the directive', function() {
var element = $compile("<ng-BrowserStack></ng-BrowserStack>")($rootScope);
$rootScope.$digest();
expect(element.html()).toContain("AngularJS testing");
});
});

Testing AngularJS Filters

Filters in AngularJS are provided to format data to be displayed in UI without changing the original format. Filters are added to an expression with the help of a pipe (“ | ”) symbol.

{{expression | filterName:parameter }}

BrowserStack Live Banner

How to do AngularJS testing using BrowserStack?

Here is a demonstration of testing real AngularJS web application, Upwork (www.upwork.com).

Let us test the Upwork application using BrowserStack Live covering different combinations of browsers and operating systems. But, if you would like to perform automation testing, sign up for BrowserStack Automate.

Step 1: Enter the URL of the application that is under test. 

Cross Browser Testing on Desktop and Mobile

Step 2: Select the combination of device and Browser 

BrowserStack Dashboard

After selecting the combination of browser and operating system, BrowserStack Live will display apps loading on actual devices for a real user experience.

Upwork on iPhone 14 plus

Upwork on iPhone 14 plus

Upwork on MacOS

Upwork on MacOS

How to do AngularJS testing using BrowserStack?

BrowserStack offers robust solutions to test AngularJS applications interactively and through automation, ensuring your app works flawlessly across different browsers and devices.

Interactive Cross-Browser Testing with BrowserStack Live

  • Simply enter the URL of your AngularJS web app on BrowserStack Live.
  • You can test your app’s behavior in real user environments by choosing from a wide range of real devices, operating systems, and browsers.
  • Interact with your app on actual devices to verify UI responsiveness, functionality, and cross-browser compatibility without any setup or maintenance hassles.

BrowserStack Automate Banner

Automating AngularJS Tests with BrowserStack Automate

  • Run your existing AngularJS test suites created with frameworks like Karma, Jasmine, Cypress, or NightwatchJS on BrowserStack Automate.
  • Execute tests in parallel across multiple browser-device combinations in the cloud, accelerating your test cycles.
  • Integrate with popular CI/CD tools like Jenkins, CircleCI, and Azure to embed automated AngularJS testing seamlessly into your development pipeline.

Benefit from detailed test reports, screenshots, and logs for faster debugging and higher test reliability.

Talk to an Expert

Conclusion

Effective AngularJS testing ensures your applications remain robust, maintainable, and user-friendly. By combining manual and automated unit, integration, and end-to-end tests, you can catch issues early and deliver high-quality software.

Leveraging modern tools and platforms like BrowserStack further simplifies testing across real devices and browsers at scale, accelerating development and improving confidence in your releases.

Tags
Automation Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord