测试角度解析方法 [英] Test Angular resolve method
问题描述
我有ui-router的Angular,所以 toResolve
变量将在我的 SomeController
中解析
I have Angular with ui-router, so toResolve
variable will be resolved in my SomeController
.state('some.state', {
url: '/some',
controller: 'SomeController',
templateUrl: '/static/views/some-state.html',
resolve: {
toResolve: function(Resource) {
return Resource.get(function(response) {
return response;
});
},
但是如何使用Jasmine测试这个功能?假设我忘记了返回
语句,因此我的范围内的 toResolve
将未定义。
But how to test this functionality with Jasmine? Let's suppose that I forget return
statement, therefore the toResolve
in my scope will be undefined.
推荐答案
使用服务使解析器可以高效测试(并且在集成/中也可以模拟) e2e测试)。
Use services to make resolvers efficiently testable (and also mockable in integration/e2e tests).
注意:角度服务是单例,状态/路由解析器不是。
如果缓存了分辨率是预期的,可以将解析器移动到 factory
服务。
If caching a resolution is expected, a resolver may be moved to factory
service.
app.factory('someResolver', function(Resource) {
return Resource.get(function(response) {
return response;
})
});
...
resolve: { toResolve: 'someResolver' },
另一方面,如果期望在每次路线更改时评估解析器,这可能会导致不良的应用行为。在这种情况下,适当的配方可能是常量
带注释的功能:
On the other hand, if the resolver is expected to be evaluated on each route change, this may lead to undesirable app behaviour. In this case the appropriate recipe may be constant
annotated function:
app.constant('someResolver', ['Resource', function(Resource) {
return Resource.get(function(response) {
return response;
})
}]);
app.config(function (someResolver, ...) {
...
resolve: { toResolve: someResolver },
...
否则规格可能以一堆样板代码结束:
Otherwise the specs may end encumbered with a pile of boilerplate code:
var toResolveFactory = $state.get('some.state').resolve.toResolve;
var toResolve = $injector.invoke(toResolveFactory);
这篇关于测试角度解析方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!