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!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
