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); }; });
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; });
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 }; }; });
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; });
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); }; });
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; });
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 }; }; });
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.
$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; });
$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) { // 服务实现 });
Simulate global objects
Global objects come from the following sources:
- Objects that are part of the global "window" object (for example, localStorage, indexedDb, Math, etc.).
- 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:
- 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); }; });
- 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; });
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 }; }; });
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; });
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
