search
HomeWeb Front-endJS TutorialHow to unit test Angular.js Controller
How to unit test Angular.js ControllerDec 09, 2016 am 09:33 AM
angular.js

1. Write a simple Angular App

Before starting to write the test, we first write a simple calculation App, which will calculate the sum of two numbers.

How to unit test Angular.js Controller

The code is as follows:

<html>
 <head>
 <script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular.min.js"></script>
 </head>
 <body>
 <!-- This div element corresponds to the CalculatorController we created via the JavaScript-->
 <div ng-controller="CalculatorController">
  <input ng-model="x" type="number">
  <input ng-model="y" type="number">
  <strong>{{z}}</strong>
  <!-- the value for ngClick maps to the sum function within the controller body -->
  <input type="button" ng-click="sum()" value="+">
 </div>
 </body>
 <script type="text/javascript">
 
 // Creates a new module called &#39;calculatorApp&#39;
 angular.module(&#39;calculatorApp&#39;, []);
 
 // Registers a controller to our module &#39;calculatorApp&#39;.
 angular.module(&#39;calculatorApp&#39;).controller(&#39;CalculatorController&#39;, function CalculatorController($scope) {
  $scope.z = 0;
  $scope.sum = function() {
  $scope.z = $scope.x + $scope.y;
  };
 });
 
 // load the app
 angular.element(document).ready(function() {
  angular.bootstrap(document, [&#39;calculatorApp&#39;]);
 });
 
 </script>
</html>

Second, briefly talk about some basic concepts involved:

Create a module

What is angular.module? It is a place for creating and recycling modules. We create a new module called calculatorApp and we add the component to this module.

angular.module(&#39;calculatorApp&#39;, []);

About the second parameter? The second parameter is required and indicates that we are creating a new module. If our application needs other dependencies, we can pass them ['ngResource', 'ngCookies']. The presence of the second parameter indicates that this is an instance of the module returned by the request.

Conceptually, it is meant to mean something like the following:

* angular.module.createInstance(name, requires);
* angular.module.getInstance(name)

However, actually we write it like this:

* angular.module(&#39;calculatorApp&#39;, []); // i.e. createInstance
* angular.module('calculatorApp'); // i.e. getInstance

More information about module https://docs.angularjs .org/api/ng/function/angular.module

2. Add a controller to the module

Then we add a controller to the angular module example

angular.module(&#39;calculatorApp&#39;).controller(&#39;CalculatorController&#39;, function CalculatorController($scope) {
 $scope.z = 0;
 $scope.sum = function() {
 $scope.z = $scope.x + $scope.y;
 };
});

The controller is mainly responsible for business logic and view binding , $scope is the direct messenger to the view's controller.

3. Connect elements in the view

In the HTML below, we need to calculate the value in the input, and these are contained in the div of this controller.

<div ng-controller="CalculatorController">
 <input ng-model="x" type="number">
 <input ng-model="y" type="number">
 <strong>{{z}}</strong>
 <!-- the value for ngClick maps to the sum function within the controller body -->
 <input type="button" ng-click="sum()" value="+">
</div>

Input The value bound to ng-model is the same as that defined on $scope, such as $scope.x. We also bound the $scope.sum method to the button element using ng-click.

3. Add tests

Next we finally get to our topic, add some unit tests to the controller. We ignore the html part of the code and focus mainly on the controller code.

angular.module(&#39;calculatorApp&#39;).controller(&#39;CalculatorController&#39;, function CalculatorController($scope) {
 $scope.z = 0;
 $scope.sum = function() {
 $scope.z = $scope.x + $scope.y;
 };
});

In order to test the controller, we need to mention the following points? + How to create a controller instance + How to get/set the properties of an object + How to call functions in $scope

describe(&#39;calculator&#39;, function () {
 
 beforeEach(angular.mock.module(&#39;calculatorApp&#39;));
 
 var $controller;
 
 beforeEach(angular.mock.inject(function(_$controller_){
 $controller = _$controller_;
 }));
 
 describe(&#39;sum&#39;, function () {
 it(&#39;1 + 1 should equal 2&#39;, function () {
  var $scope = {};
  var controller = $controller(&#39;CalculatorController&#39;, { $scope: $scope });
  $scope.x = 1;
  $scope.y = 2;
  $scope.sum();
  expect($scope.z).toBe(3);
 });
 });
 
});

Before we start, we need to introduce ngMock. We add angular.mock

, ngMock to the test code Modules provide a mechanism for unit testing of virtual services.

4. How to get the controller instance

Using ngMock we can register a calculator app instance.

beforeEach(angular.mock.module(&#39;calculatorApp&#39;));

Once the calculatorApp is initialized, we can use the inject function, which can solve the controller reference problem.

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

Once the app is loaded, we use the inject function, and the $controller service can obtain an instance of CalculatorController.

var controller = $controller(&#39;CalculatorController&#39;, { $scope: $scope });

5. How to get/set the attributes of an object

In the previous code, we can already get an instance of a controller. The second parameter in the brackets is actually the controller itself. Our controller only has A parameter $scope object

function CalculatorController($scope) { ... }

In our test $scope represents a simple JavaScript object.

var $scope = {};
var controller = $controller(&#39;CalculatorController&#39;, { $scope: $scope });
// set some properties on the scope object
$scope.x = 1;
$scope.y = 2;

We set the values ​​of x and y to simulate what is shown in the gif just now. We agree that we can also read the properties in the object, just like the assertion in the following test:

expect($scope.z).toBe(3);

6. How to call the functions in $scope

The last thing is how we simulate the user’s click , just like what we use in most JS, it is actually just a simple call to the function,

$scope.sum();

How to unit test Angular.js Controller


Statement
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
Angular学习之聊聊独立组件(Standalone Component)Angular学习之聊聊独立组件(Standalone Component)Dec 19, 2022 pm 07:24 PM

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

手把手带你了解Angular中的依赖注入手把手带你了解Angular中的依赖注入Dec 02, 2022 pm 09:14 PM

本篇文章带大家了解一下依赖注入,介绍一下依赖注入解决的问题和它原生的写法是什么,并聊聊Angular的依赖注入框架,希望对大家有所帮助!

Angular的:host、:host-context、::ng-deep选择器Angular的:host、:host-context、::ng-deep选择器May 31, 2022 am 11:08 AM

本篇文章带大家深入了解一下angular中的几个特殊选择器:host、:host-context、::ng-deep,希望对大家有所帮助!

深入了解angular中的@Component装饰器深入了解angular中的@Component装饰器May 27, 2022 pm 08:13 PM

Component是Directive的子类,它是一个装饰器,用于把某个类标记为Angular组件。下面本篇文章就来带大家深入了解angular中的@Component装饰器,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function