gpt4 book ai didi

在 Angular 中对指令 Controller 进行单元测试,而不使 Controller 成为全局的

转载 作者:行者123 更新时间:2023-12-02 08:35:25 24 4
gpt4 key购买 nike

在 Vojta Jina 的优秀存储库中,他演示了指令测试,他在模块包装器之外定义了指令 Controller 。看这里: https://github.com/vojtajina/ng-directive-testing/blob/master/js/tabs.js

这不是不好的做法并且会污染全局命名空间吗?

如果在另一个地方调用 TabsController 可能是合乎逻辑的,那不会破坏东西吗?

上述指令的测试可以在这里找到:https://github.com/vojtajina/ng-directive-testing/commit/test-controller

是否可以将指令 Controller 与指令的其余部分分开进行测试,而不将 Controller 放置在全局命名空间中?

最好将整个指令封装在 app.directive(...) 定义中。

最佳答案

有时我更喜欢将 Controller 与指令一起包含在内,因此我需要一种方法来测试它。

首先是指令

angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'EA',
scope: {},
controller: function ($scope) {
$scope.isInitialized = true
},
template: '<div>{{isInitialized}}</div>'
}
})

然后是测试:

describe("myDirective", function() {
var el, scope, controller;

beforeEach inject(function($compile, $rootScope) {
# Instantiate directive.
# gotacha: Controller and link functions will execute.
el = angular.element("<my-directive></my-directive>")
$compile(el)($rootScope.$new())
$rootScope.$digest()

# Grab controller instance
controller = el.controller("myDirective")

# Grab scope. Depends on type of scope.
# See angular.element documentation.
scope = el.isolateScope() || el.scope()
})

it("should do something to the scope", function() {
expect(scope.isInitialized).toBeDefined()
})
})

参见angular.element documentation了解从实例化指令获取数据的更多方法。

请注意,实例化该指令意味着 Controller 和所有链接函数都已经运行,因此这可能会影响您的测试。

关于在 Angular 中对指令 Controller 进行单元测试,而不使 Controller 成为全局的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15314293/

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