角控制器:如何这些魔术方法在这个单元测试工作吗? [英] Angular Controllers: How are these magic methods working in this unit test?

查看:100
本文介绍了角控制器:如何这些魔术方法在这个单元测试工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面code两个片段,从单元上的角文档测试


  

在角控制器被严格从这导致一个更容易测试性故事如在这个例子中可以看出,DOM操作逻辑分隔:


 函数PasswordCtrl($范围){
  $ scope.password ='​​';
  $ scope.grade =功能(){
    变种大小= $ scope.password.length;
    如果(大小→8){
      $ scope.strength =强;
    }否则如果(大小→3){
      $ scope.strength ='媒介';
    }其他{
      $ scope.strength =弱;
    }
  };
}


  

和测试是直线前进


  VAR PC =新PasswordCtrl();
pc.password('ABC');
pc.grade();
期待(pc.strength).toEqual('弱');

我想知道如何二号code段工作。没有模拟$范围传递给它,但显然它的工作原理。此外,该方法调用 pc.password('ABC'); pc.grade()似乎是别名 $ scope.password('ABC') $ scope.grade(),但如果做这些别名从何而来?这是不是内置的角度?以下介绍一种相当于红宝石的method_missing?如果是这样,它是如何引擎盖下工作吗?


解决方案

没有,它不象​​正常工作。我碰到下面的错误,如果我简单地粘贴你有什么这里成2个文件,并告诉因缘来运行它。错误,符合市场预期,是:

 铬26.0(苹果机)ERROR
    未捕获类型错误:无法设置的未定义的属性'密码'
    在/Volumes/.../utest/test/ctrl.js:2铬
26.0(苹果机):执行的0误差0(0.173秒/ 0秒)

其中, ctrl.js:2 是:

  $ scope.password ='​​';

该AngularJS文档遗憾的是并不清楚。所有的测试必须采取内部发生一个描述块,因此文件必须假定读者知道嘲笑在 beforeEach <所需的$范围/ code>块。

Consider the two snippets of code below, taken from the angular docs on unit testing:

In angular the controllers are strictly separated from the DOM manipulation logic which results in a much easier testability story as can be seen in this example:

function PasswordCtrl($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';
    }
  };
}

and the test is straight forward

var pc = new PasswordCtrl();
pc.password('abc');
pc.grade();
expect(pc.strength).toEqual('weak');

I want to know how the 2nd code snippet is working. No mock $scope is passed to it, and yet apparently it works. Also the method calls pc.password('abc'); and pc.grade() seem to be aliases for $scope.password('abc') and $scope.grade(), but where do these aliases come from? Is this something built into angular? A sort of equivalent to ruby's method_missing? If so, how does it work under the hood?

解决方案

No, it does not work as is. I get the following error if I simply paste what you have here into 2 files and tell karma to run it. Error, as expected, is:

Chrome 26.0 (Mac) ERROR
    Uncaught TypeError: Cannot set property 'password' of undefined
    at /Volumes/.../utest/test/ctrl.js:2 Chrome
26.0 (Mac): Executed 0 of 0 ERROR (0.173 secs / 0 secs)

where ctrl.js:2 is:

  $scope.password = '';

The AngularJS documentation is unfortunately not clear. All the test must take place inside a describe block and therefore the documentation must have assumed that the reader know to mock the $scope needed in a beforeEach block.

这篇关于角控制器:如何这些魔术方法在这个单元测试工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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