gpt4 book ai didi

javascript - 如何在指令 UT 中模拟所需的指令 Controller

转载 作者:行者123 更新时间:2023-11-28 09:09:24 24 4
gpt4 key购买 nike

根据 AngularJS 文档,指令 Controller 是:

instantiated before the pre-linking phase and it is shared with other directives if they request it by name (see require attribute). This allows the directives to communicate with each other and augment each other's behavior.

在 UI View 由容器和小部件组成的情况下,这听起来很棒且有用,小部件的链接函数可以通过声明性方法 require:^cotnainerDirective 在容器指令 Controller 中传递。这提供了回调容器行为的替代方法,而不是依赖事件的通信。

例如,一个需要容器 Controller 的小部件指令如下:

angular.module('platform').directive('widget', [ function ( ) {
return {
restrict: 'E',
transclude: true,
require: '?^container',
replace: true,
scope: {
layout: '=',
model: '='
},
templateUrl: 'js/modules/platform/templates/form-tmpl.html',
link: function (scope, element, iAttrs, requiredCtrl) {
if(requiredCtrl && requiredCtrl.fooMethod){
....
}
}
};
}]);

如果小部件位于容器内,则链接函数内的代码将执行额外的工作。该代码运行良好。然而,在对 widget 指令进行单元测试时,很难想到发送模拟容器指令 Controller 的好方法,因为它不是通过 Angular $injector 服务注入(inject)的。

可能,我需要从容器的 Angular 编写 UT,但这在某种程度上涉及引导容器指令所需的太多准备工作。有人以前遇到过这种情况并可以在这里分享一些好的观点吗?

最佳答案

事实证明,如果我想对小部件指令进行单元测试,它必须与容器松散地解耦,在这种情况下使用“require”并不是一个好主意,因为它实际上使小部件指令紧密依赖于容器。我已经改变了我的设计以使用事件驱动的通信 btw widget 和容器,这样我就可以简单地模拟事件监听器来监视 UT 中 widget 指令发送的事件。

关于javascript - 如何在指令 UT 中模拟所需的指令 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16514045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com