>  기사  >  웹 프론트엔드  >  Angular.js 컨트롤러를 단위 테스트하는 방법

Angular.js 컨트롤러를 단위 테스트하는 방법

高洛峰
高洛峰원래의
2016-12-09 09:33:401167검색

1. 간단한 Angular 앱 작성

테스트 작성을 시작하기 전에 먼저 두 숫자의 합을 계산하는 간단한 계산 앱을 작성합니다.

Angular.js 컨트롤러를 단위 테스트하는 방법

코드는 다음과 같습니다.

<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>

2. 몇 가지 기본 개념에 대해 간단히 이야기해 보세요. 관련 :

모듈 만들기

angular.module이 무엇인가요? 모듈을 제작하고 재활용하는 곳입니다. CalculatorApp이라는 새 모듈을 만들고 이 모듈에 구성 요소를 추가합니다.

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

두 번째 매개변수에 대해서요? 두 번째 매개변수는 필수이며 새 모듈을 생성한다는 것을 나타냅니다. 애플리케이션에 다른 종속성이 필요한 경우 ['ngResource', 'ngCookies']를 전달할 수 있습니다. 두 번째 매개변수가 있으면 이것이 요청에 의해 반환된 모듈의 인스턴스임을 나타냅니다.

개념적으로는 다음과 같은 뜻입니다.

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

그러나 실제로는 이렇게 씁니다. >

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

모듈에 대한 추가 정보 https://docs.angularjs.org/api/ng/function/angular.module

2. 컨트롤러 추가


모듈에

angular.module(&#39;calculatorApp&#39;).controller(&#39;CalculatorController&#39;, function CalculatorController($scope) {
 $scope.z = 0;
 $scope.sum = function() {
 $scope.z = $scope.x + $scope.y;
 };
});
컨트롤러를 추가합니다.

컨트롤러는 주로 비즈니스 로직을 담당합니다. 뷰에 바인딩되어 있으며 $scope는 뷰 컨트롤러에 대한 직접적인 메신저입니다.

3. 뷰의 요소를 연결합니다.


아래 HTML에서 입력 값을 계산해야 하며 이는 이 컨트롤러의 div에 포함되어 있습니다.

<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>

입력에서 ng-model에 바인딩된 값은 $scope.x와 같은 $scope에 정의되며 버튼 요소에서도 사용됩니다. ng-click은 $scope.sum 메소드에 바인딩됩니다.

3. 테스트 추가


마침내 주제에 도달하여 컨트롤러에 몇 가지 단위 테스트를 추가합니다. 코드의 html 부분을 무시하고 주로 컨트롤러 코드에 중점을 둡니다. .

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

컨트롤러를 테스트하기 위해서는 다음 사항을 언급해야 겠죠? + 컨트롤러 인스턴스를 생성하는 방법 + 객체의 속성을 가져오거나 설정하는 방법 + $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);
 });
 });
 
});

시작하기 전에 , ngMock을 도입해야 합니다. 테스트 코드에 angle.mock

을 추가했습니다. ngMock 모듈은 가상 서비스의 단위 테스트를 위한 메커니즘을 제공합니다.

4. 컨트롤러 인스턴스를 가져오는 방법


ngMock을 사용하여 계산기 앱 인스턴스를 등록할 수 있습니다.

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

calculatorApp이 초기화되면 주입 기능을 사용하여 컨트롤러 참조 문제를 해결할 수 있습니다.

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

앱이 로드되면 주입 기능을 사용하고 $controller 서비스는 CalculatorController의 인스턴스를 얻을 수 있습니다.

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

5. 객체의 속성을 가져오거나 설정하는 방법


이전 코드에서 이미 가져올 수 있습니다. an 컨트롤러의 경우 괄호 안의 두 번째 매개변수는 실제로 컨트롤러 자체입니다. $scope 객체

function CalculatorController($scope) { ... }

테스트 $scope는 간단한 JavaScript 객체를 나타냅니다.

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

방금 gif에 표시된 내용을 시뮬레이션하기 위해 x와 y의 값을 설정했습니다. 우리는 다음 테스트의 주장처럼 객체의 속성을 읽을 수도 있다는 데 동의합니다.

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

6. 에서 함수를 호출하는 방법 $scope


마지막으로 사용자의 클릭을 시뮬레이션하는 방법은 대부분의 JS에서 사용하는 것과 마찬가지로 실제로는 단순한 호출 함수입니다.

$scope.sum();

Angular.js 컨트롤러를 단위 테스트하는 방법


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.