Home > Web Front-end > JS Tutorial > Mocking Dependencies in AngularJS Tests

Mocking Dependencies in AngularJS Tests

Jennifer Aniston
Release: 2025-02-20 12:28:16
Original
360 people have browsed it

Mocking Dependencies in AngularJS Tests

Core points

  • AngularJS is born with testing in mind, and its built-in dependency injection mechanism allows each component to be tested using any JavaScript testing framework (such as Jasmine).
  • Mocks in unit tests involve the ability to isolate test code snippets, which can be challenging because the dependencies come from different sources. Simulation in AngularJS is simplified with the angular-mocks module, which provides simulations for a set of commonly used AngularJS services.
  • Service simulation in AngularJS can be accomplished by obtaining instances of actual services and listening to services, or using $provide to implement simulation services. The latter method is preferable, which can avoid calling the actual method implementation of the service.
  • Provider simulation in AngularJS follows similar rules as service simulation. The $get method must be implemented in the test. If the function defined in the $get function is not required in the test file, it can be assigned a value to an empty function.
  • Global objects (such as part of a global "window" object or objects created by third-party libraries) can be simulated by injecting them into $window or using a global object to create values ​​or constants and injecting them as needed.

AngularJS design concept includes testing. The source code of the framework is very well tested, and any code written using the framework is also testable. The built-in dependency injection mechanism makes it possible to test every component written in AngularJS. Code in AngularJS applications can be unit tested using any existing JavaScript testing framework. The most common framework used to test AngularJS code is Jasmine. All sample code snippets in this article are written using Jasmine. If you use any other testing framework in your Angular project, you can still apply the ideas discussed in this article.

This article assumes that you already have experience in unit testing and testing AngularJS code. You don't have to be a testing expert. If you have a basic understanding of testing and can write some simple test cases for AngularJS applications, you can continue reading this article.

The role of simulation in unit testing

The task of each unit tests is to test the functionality of a piece of code in isolation. Isolating the system under test can sometimes be challenging because dependencies can come from different sources and we need to fully understand the responsibilities of the object to be simulated.

In non-statically typed languages ​​such as JavaScript, simulation is difficult because it is not easy to understand the structure of the object to be simulated. At the same time, it also provides flexibility, that is, to simulate only a part of the object currently in use by the system under test, and ignore the rest.

Mock in AngularJS Test

Since one of the main goals of AngularJS is testability, the core team puts extra effort into this to make testing easier and provides us with a set of simulations in the angular-mocks module. This module contains simulations around a set of AngularJS services (such as $http, $timeout, $animate, etc.) that are widely used in any AngularJS application. This module reduces the amount of time it takes for developers to write tests.

These simulations are very helpful when writing tests for real business applications. At the same time, they are not enough to test the entire application. We need to mock any dependencies in the framework but not mocked - dependencies from third-party plugins, global objects, or dependencies created in the application. This article will introduce some tips on mocking AngularJS dependencies.

Simulation Service

Services are the most common dependency type in AngularJS applications. As you probably already know, services are an overloaded term in AngularJS. It may refer to a service, factory, value, constant, or provider. We will discuss the provider in the next section. The service can be simulated in one of the following ways:

  • Methods to use injection blocks to get instances of actual service and listen to service.
  • Use $provide to implement simulation services.

I don't like the first method because it may lead to the actual method implementation of the calling service. We will use the second method to simulate the following service:

angular.module('sampleServices', [])
  .service('util', function() {
    this.isNumber = function(num) {
      return !isNaN(num);
    };

    this.isDate = function(date) {
      return (date instanceof Date);
    };
  });
Copy after login
Copy after login
Copy after login

The following code snippet creates a simulation of the above service:

module(function($provide) {
  $provide.service('util', function() {
    this.isNumber = jasmine.createSpy('isNumber').andCallFake(function(num) {
      // 模拟实现
    });
    this.isDate = jasmine.createSpy('isDate').andCallFake(function(num) {
      // 模拟实现
    });
  });
});

// 获取模拟服务的引用
var mockUtilSvc;

inject(function(util) {
  mockUtilSvc = util;
});
Copy after login
Copy after login
Copy after login

Although the above example uses Jasmine to create spies, you can replace it with Sinon.js to achieve the equivalent functionality.

It is best to create all the simulations after loading all modules required for the test. Otherwise, if a service is defined in a loaded module, the actual implementation overrides the simulated implementation.

Constants, factories, and values ​​can be simulated separately using $provide.constant, $provide.factory and $provide.value.

Simulation Provider

The simulation provider is similar to the simulation service. All rules that must be followed when writing providers must also be followed when mocking them. Consider the following provider:

angular.module('mockingProviders',[])
  .provider('sample', function() {
    var registeredVals = [];

    this.register = function(val) {
      registeredVals.push(val);      
    };

    this.$get = function() {
      function getRegisteredVals() {
        return registeredVals;
      }

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
Copy after login
Copy after login
Copy after login

The following code snippet creates a simulation for the above provider:

module(function($provide) {
  $provide.provider('sample', function() {
    this.register = jasmine.createSpy('register');

    this.$get = function() {
      var getRegisteredVals = jasmine.createSpy('getRegisteredVals');

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
});

// 获取提供程序的引用
var sampleProviderObj;

module(function(sampleProvider) {
  sampleProviderObj = sampleProvider;
});
Copy after login
Copy after login
Copy after login

The difference between getting references to the provider and other singletons is that the provider is not available in the inject() block at this time, because the provider is converted to a factory at this time. We can use the module() block to get their objects.

In the case of defining a provider, the $get method must also be implemented in the test. If you do not need the function defined in the $get function in the test file, you can assign it to an empty function.

Analog Module

If the module to be loaded in the test file requires a bunch of other modules, the module under test cannot be loaded unless all the required modules are loaded. Loading all of these modules sometimes causes tests to fail because some actual service methods may be called from the test. To avoid these difficulties, we can create virtual modules to load the measured modules.

For example, suppose the following code represents a module with the example service added:

angular.module('sampleServices', [])
  .service('util', function() {
    this.isNumber = function(num) {
      return !isNaN(num);
    };

    this.isDate = function(date) {
      return (date instanceof Date);
    };
  });
Copy after login
Copy after login
Copy after login

The following code is the beforeEach block in the test file of the sample service:

module(function($provide) {
  $provide.service('util', function() {
    this.isNumber = jasmine.createSpy('isNumber').andCallFake(function(num) {
      // 模拟实现
    });
    this.isDate = jasmine.createSpy('isDate').andCallFake(function(num) {
      // 模拟实现
    });
  });
});

// 获取模拟服务的引用
var mockUtilSvc;

inject(function(util) {
  mockUtilSvc = util;
});
Copy after login
Copy after login
Copy after login

Alternatively, we can add the simulated implementation of the service to the virtual module defined above.

Simulate the method to return to Promise

Writing an end-to-end Angular application can be difficult without using Promise. Testing snippets of code that rely on methods that return Promise becomes a challenge. A normal Jasmine spy causes some test cases to fail because the function under test expects an object with the actual Promise structure.

Asynchronous methods can be simulated using another asynchronous method that returns a Promise with a static value. Consider the following factories:

angular.module('mockingProviders',[])
  .provider('sample', function() {
    var registeredVals = [];

    this.register = function(val) {
      registeredVals.push(val);      
    };

    this.$get = function() {
      function getRegisteredVals() {
        return registeredVals;
      }

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
Copy after login
Copy after login
Copy after login

We will test the getData() function in the above factory. As we can see, it relies on the method of serving dataSourceSvc getAllItems(). We need to simulate services and methods before testing the functionality of the getData() method.

The

$q service has when() and reject() methods that allow the use of static values ​​to resolve or reject Promise. These methods are very useful in testing mocking methods that return Promise. The following code snippet simulates dataSourceSvc factory:

module(function($provide) {
  $provide.provider('sample', function() {
    this.register = jasmine.createSpy('register');

    this.$get = function() {
      var getRegisteredVals = jasmine.createSpy('getRegisteredVals');

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
});

// 获取提供程序的引用
var sampleProviderObj;

module(function(sampleProvider) {
  sampleProviderObj = sampleProvider;
});
Copy after login
Copy after login
Copy after login

$q Promise completes its operation after the next digest cycle. The digest cycle runs continuously in the actual application, but not in the test. Therefore, we need to call $rootScope.$digest() manually to enforce the Promise. The following code snippet shows a sample test:

angular.module('first', ['second', 'third'])
  // util 和 storage 分别在 second 和 third 中定义
  .service('sampleSvc', function(utilSvc, storageSvc) {
    // 服务实现
  });
Copy after login

Simulate global objects

Global objects come from the following sources:

  1. Objects that are part of the global "window" object (for example, localStorage, indexedDb, Math, etc.).
  2. Objects created by third-party libraries such as jQuery, underscore, moment, breeze, or any other libraries.

By default, global objects cannot be simulated. We need to follow certain steps to make them simulateable.

We may not want to simulate Math objects or utility objects (created by the Underscore library) because their operations do not perform any business logic, operate the UI, and do not communicate with the data source. However, objects such as $.ajax, localStorage, WebSockets, breeze, and toastr must be simulated. Because if these objects are not mocked, they will perform their actual operations when performing unit tests, which can lead to some unnecessary UI updates, network calls, and sometimes errors in the test code. _

Due to dependency injection, every part of the code written in Angular is testable. DI allows us to pass any object that follows the actual object shim, just so that the tested code will not break when executed. If global objects can be injected, they can be simulated. There are two ways to make global objects injectable:

  1. Inject $window into the service/controller that requires the global object and access the global object through $window. For example, the following services use localStorage via $window:
angular.module('sampleServices', [])
  .service('util', function() {
    this.isNumber = function(num) {
      return !isNaN(num);
    };

    this.isDate = function(date) {
      return (date instanceof Date);
    };
  });
Copy after login
Copy after login
Copy after login
  1. Create a value or constant using a global object and inject it where it is needed. For example, the following code is a constant for toastr:
module(function($provide) {
  $provide.service('util', function() {
    this.isNumber = jasmine.createSpy('isNumber').andCallFake(function(num) {
      // 模拟实现
    });
    this.isDate = jasmine.createSpy('isDate').andCallFake(function(num) {
      // 模拟实现
    });
  });
});

// 获取模拟服务的引用
var mockUtilSvc;

inject(function(util) {
  mockUtilSvc = util;
});
Copy after login
Copy after login
Copy after login

I prefer to wrap global objects with constants rather than values, because constants can be injected into configuration blocks or providers, and constants cannot be decorated.

The following code snippet shows the simulation of localStorage and toastr:

angular.module('mockingProviders',[])
  .provider('sample', function() {
    var registeredVals = [];

    this.register = function(val) {
      registeredVals.push(val);      
    };

    this.$get = function() {
      function getRegisteredVals() {
        return registeredVals;
      }

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
Copy after login
Copy after login
Copy after login

Conclusion

Mock is one of the important components of writing unit tests in any language. As we have seen, dependency injection plays an important role in testing and simulation. The code must be organized in a way so that its functionality can be easily tested. This article lists the most common set of objects to simulate when testing AngularJS applications. The code related to this article can be downloaded from GitHub.

FAQ on mocking dependencies in AngularJS tests (FAQ)

What is the purpose of mocking dependencies in AngularJS testing?

Mocking dependencies in AngularJS testing is a key part of unit testing. It allows developers to isolate the tested code and simulate the behavior of their dependencies. This way, you can test how your code interacts with its dependencies without actually calling them. This is especially useful when dependencies are complex, slow, or have side effects you want to avoid during testing. By mocking these dependencies, you can focus on testing the functionality of your code in a controlled environment.

How to create a mock service in AngularJS?

Creating a mock service in AngularJS involves using the $provide service in module configuration. You can use the $provide service's value, factory or service methods to define a simulated implementation of a service. Here is a basic example:

module(function($provide) {
  $provide.provider('sample', function() {
    this.register = jasmine.createSpy('register');

    this.$get = function() {
      var getRegisteredVals = jasmine.createSpy('getRegisteredVals');

      return {
        getRegisteredVals: getRegisteredVals
      };
    };
  });
});

// 获取提供程序的引用
var sampleProviderObj;

module(function(sampleProvider) {
  sampleProviderObj = sampleProvider;
});
Copy after login
Copy after login
Copy after login

In this example, we use the $provide.value method to define the simulated implementation of myService. During testing, this mock service will be used instead of the actual service.

(Please ask the rest of the FAQ questions one by one due to space limitations, and I will try my best to provide concise and clear answers.)

The above is the detailed content of Mocking Dependencies in AngularJS Tests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template