问题描述
我想要测试一些意见,正在使用<一个UI的SREF ='someState'>链接< / 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
?这将是容易的,在我的控制器这样使用 $状态
时:
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?
推荐答案
我发现它自己。在看看到角UI路由器源$ C $ C后,我发现了 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.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路由器:测试用户界面,SREF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!