测试 Angular 解析方法 [英] 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 测试此功能?假设我忘记了 return
语句,因此范围内的 toResolve
将是 undefined.
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).
注意:Angular 服务是单例的,状态/路由解析器不是.
如果需要缓存解析,解析器可能会移至 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' },
另一方面,如果期望在每次路由更改时评估解析器,这可能会导致不良的应用行为.在这种情况下,适当的配方可能是 constant
注释函数:
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);
这篇关于测试 Angular 解析方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!