问题描述
好吧,所以我一直对一些问题的绊脚石很长一段时间,我想听听来自社会其他成员的意见。
Alright, so I have been stumbling upon some issue for a long time and I would like to hear an opinion from the rest of community.
首先,让我们看看一些抽象的控制器。
First, let's look at some abstract controller.
function Ctrl($scope, anyService) {
$scope.field = "field";
$scope.whenClicked = function() {
util();
};
function util() {
anyService.doSmth();
}
}
显然,我们在这里:
Clearly we have here:
- 常规支架的控制器
$范围
和一些服务性注入 - 某些领域和附着范围功能
- 私有方法
UTIL()
- regular scaffold for controller with
$scope
and some service injected - some field and function attached to the scope
- private method
util()
现在,我想管这个类的单元测试(茉莉花)。然而,问题是,我要验证,当我点击(呼叫 whenClicked()
)的一些项目的 UTIL()
方法将被调用。我不知道该怎么做,因为茉莉花测试我总是收到错误,无论是模拟的 UTIL()
尚未定义或者不叫
Now, I'd like to cover this class in unit tests (Jasmine). However, the problem is that I want to verify that when I click (call whenClicked()
) some item that the util()
method will be called. I don't know how to do that, since in Jasmine tests I'm always getting errors that either the mock for util()
hasn't been defined or was not called.
注意:我并不想解决这个特殊的例子,我问一般的测试这样的code模式。所以,请不要告诉我什么是确切的错误。我问怎么做,而不是如何解决这个问题。
我一直试图解决此许多方式:
I have been trying a number of ways around this:
- 很明显,我不能使用
$范围
在我的单元测试,因为我没有这个功能,连接到该对象(通常使用消息结束预计间谍,但得到未定义
或类似) - 我试图通过连接到控制器对象的功能
Ctrl.util = util的;
,然后验证像嘲弄Ctrl.util = jasmine.createSpy ()
但在这种情况下,Ctrl.util
不被调用,所以测试失败 - 我试图改变
UTIL()
附加到这个
对象和嘲讽Ctrl.util
再次,没有运气
- obviously I cannot use
$scope
in my unit tests as I don't have this function attached to this object (it usually ends with messageExpected spy but got undefined
or similar) - I tried attaching those functions to the controller object via
Ctrl.util = util;
and then verifying mocks likeCtrl.util = jasmine.createSpy()
but in this caseCtrl.util
is not being called so tests fail - I tried to change
util()
to be attached tothis
object and mockingCtrl.util
again, with no luck
好吧,我找不到我的身边就这样,我希望从JS忍者一些帮助,工作小提琴将是完美的。
Well, I cannot find my way around this, I would expect some help from JS ninjas, a working fiddle would be perfect.
推荐答案
命名空间上它的范围是污染。你想要做的是提取逻辑放到一个单独的函数,然后注入到你的控制器。即。
Namespacing it on the scope is pollution. What you want to do is extract that logic into a separate function which is then injected into your Controller. i.e.
function Ctrl($scope, util) {
$scope.field = "field";
$scope.whenClicked = function() {
util();
};
}
angular.module("foo", [])
.service("anyService", function(...){...})
.factory("util", function(anyService) {
return function() {
anyService.doSmth();
};
});
现在你可以用单元测试嘲笑你的Ctrl键的以及UTIL。
Now you can unit test with mocks your Ctrl as well as "util".
这篇关于如何写在AngularJs私有方法测试的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!