角JS单元测试控制器 [英] angular JS unit testing a controller

查看:121
本文介绍了角JS单元测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个控制器

    (function(){
        var app = angular.module('app', []);

        app.directive('test', function(){
            return {
                restrict: 'E',
                templateUrl: 'test.html',
                controller: ['$scope', function ($scope) {
        $scope.password = '';
        $scope.grade = function() {
             var size = $scope.password.length;
           if (size > 8) {
          $scope.strength = 'strong';
            } else if (size > 3) {
          $scope.strength = 'medium';
          } else {
          $scope.strength = 'weak';
        }
      }
    }];
    });

我写一个单元测试该控制器

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('$scope', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

我结束了越来越它说的错误
错误:[NG:AREQ]参数'$范围不是一个函数,得到了不确定

I am ending up getting an error which says Error:[ng:areq] Argument '$scope' is not a function, got undefined

我要我以正确的方式,请帮助

I am I going in the right way please help

推荐答案

您控制器被定义为你的指令定义的一部分,我不相信这些都可以单元独立指令themsleves的测试。

Your controller is defined as a part of your directive definition, and I do not believe that these can be unit tested independently of the directive themsleves.

如果你想进行单元测试此控制器,你应该给它采用了棱角分明的控制器方法单独的名称,然后按名称用它在你的指令。然后,您可以使用角模拟的 $控制器类似于你现在该怎么做服务检索控制器。最终的结果是这样的:

If you want to unit test this controller, you should give it a separate name using angular's controller method, then use it in your directive by name. Then you can retrieve the controller using angular-mock's $controller service similar to how you do it now. the end result looks like:

app.controller('YourCtrl', ['$scope', function($scope) { ... }]);
app.directive('test', function() {
   return {
          ...
          controller: 'YourCtrl',
          ...
   }});

和在试验

var controller = $controller('YourCtrl', { $scope: $scope });

下面是一个的jsfiddle的把它一起

Here is a jsFiddle that puts it all together

这篇关于角JS单元测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆