AngularJS ui-router:测试 ui-sref [英] AngularJS ui-router: Test ui-sref
问题描述
我正在尝试测试一些视图,它们使用 <a ui-sref='someState'>link</a>
链接到我的应用程序中的其他状态.在我的测试中,我触发了对这些元素的点击,如下所示:
I'm trying to test some views, that are using <a ui-sref='someState'>link</a>
to link to other states in my application. In my tests I'm triggering a click on this elements like this:
element.find('a').click()
如果状态切换到someState
,我该如何测试?像这样在我的控制器中使用 $state
会很容易:
How do I test, if the state is switched to someState
? It would be easy, when using $state
in my controller like this:
// in my view
<a ng-click="goTo('someState')">link</a>
// in my controller
$scope.goTo = function(s) {
$state.go(s)
};
// in my tests
spyOn($state, 'go');
element.find('a').click()
expect($state.go).toHaveBeenCalled()
但是当我使用 ui-sref
时,我不知道要监视什么对象.如何验证我的应用程序处于正确的状态?
But when I use ui-sref
I don't know what object to spy on. How can I verify, that my application is in the right state?
推荐答案
我自己找到的.在查看了 Angular ui 路由器源代码后,我在 ui-sref
指令中发现了这一行:
I found it myself. After having a look into the angular ui router source code, I found this line inside the ui-sref
directive:
// angular-ui-router.js#2939
element.bind("click", function(e) {
var button = e.which || e.button;
if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
$timeout(function() {
$state.go(ref.state, params, options);
});
e.preventDefault();
}
});
当元素收到点击时,$state.go
被包装在 $timout
回调中.因此,在您的测试中,您必须注入 $timeout
模块.然后像这样执行 $timeout.flush()
:
When the element receives a click, the $state.go
is wrapped in a $timout
callback. So, in your tests, you have to inject the $timeout
module. Then just do a $timeout.flush()
like this:
element.find('a').click();
$timeout.flush();
expect($state.is('someState')).toBe(true);
这篇关于AngularJS ui-router:测试 ui-sref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!